Increment a number represented by an array of digits by 1

Given an integer array of variable length like [9, 8, 8, 3] where each item could be 0 to 9, write a function that would interpret the array [9, 8, 8, 3] as a number 9883 and increment it by 1. The return of the function would be an integer array containing the addition like [9, 8, 8, 4].

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] num = { 9, 9, 9 };
            int sum = 0, carryover = 0; string result = "";
            for (int i = num.Length - 1; i >= 0; i--)
            {
                if (i == num.Length - 1)
                {
                    sum = num[i] + 1;
                }

                else
                {
                    sum = num[i] + carryover;
                }
                result = (sum % 10).ToString() + result;
                carryover = sum / 10;
            }

            if (carryover > 0)
            {
                result = carryover.ToString() + result;
            }
            int[] ia = new int[result.Length];
            for (int i = 0; i < result.Length; i++)
            {
                ia[i] = int.Parse(result[i].ToString());
                Console.Write(ia[i]);
            }
            Console.WriteLine();
        }
    }
}

Output
=======
1000
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s