Problem
You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Approach
It may look like a simple solution of simply adding 1
to the last number - but you have to account for the number being 9
. If this is the case you'd need to carry the 1 and thus incrementing the next number.
This "carrying" would need to be done, for all the 9's
, so if we had numbers like 999
, it would need to be incremented and an extra number added to create [1,0,0,0]
So, if the current number is lower than 9, we can simply increment it by 1 and end the loop, returning the array of digits.
If it's equal to 9, we set it to 1 and move onto the next digit (i.e carrying the 1 - that then get's added to , and returns the new array).
Edge Case
If all numbers are 9, it'll iterate all the way through to the end of the loop, at which point we've handled this eventuality and then add a 1
to the beginning of the array.
Code
public int[] PlusOne(int[] digits)
{
for (int i = digits.Length - 1; i >= 0; i--)
{
if (digits[i] < 9)
{
digits[i]++;
return digits;
}
else
{
digits[i] = 0;
}
}
int[] newDigits = new int[digits.Length + 1];
newDigits[0] = 1;
return newDigits;
}
Top comments (0)