Plus one to array of digits

By   Tewodros   Date Posted: Nov. 2, 2023  Hits: 442   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given a list of numbers as an array  treat it as a whole number and add one to it  and return the result as an array

Example

Input [9,9,9 ]

Output [1,0,0,0]

Example

Input [8,9,9]

output [9,0,0]

public  int[] PlusOne(int[] nums)

{

  

     int[] result = new int[nums.Length+1];


 

     bool carry = false;

     bool first = true;

     for (int i = nums.Length-1; i>=0; i--)

     {

       if (first && nums[i] == 9)

         {

             result[i+1] = 0;

             carry = true;

         }

      else

         {

             if (carry || first)

             {

                 result[i+1] = nums[i] + 1;

                 first = false;

                 carry = false;

             }

             else

                 result[i+1] = nums[i];

         }

     }

     if (carry)

         result[0] = 1;


 

     if (result[0] == 0)

     {

         int[] res = new int[nums.Length];

         for (int i = 0; i < result.Length-1; i++)

         {

          res[i] = result[i + 1];

            

         }

         return res;

     }


 

     return result;

         

  }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* xcisgc

Back to Top