66_Plus One
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
Example
Solution 1: brute force
Start with the rightmost digit and work to the left, and specify carry value for each move
If the sum is 10, replace the digit with 0, and set carry be 1
If the sum less than 10, add current carry to the digit, and set carry be 0
After looping all digits, if carry = 1, add 1 at the beginning of digits
time complexity:
Solution 2: advanced
A fact to notice is when carry = 0, it will stay at 0 always. All the digits on the left of that element keeps the same.
Solution 3: convert the list to integer
Convert list to integer
Plus one to the integer
Convert back to a list
Note: this method might cause a overflow problem, i.e. if the integer is too large to store, it will cause an error.
Last updated