Title Link: Plus One
Given a non-negative number represented as an array of digits, plus one to the number.
The digits is stored such, the most significant digit was at the head of the list.
The requirement of this problem is given an array to represent a nonnegative integer whose high position precedes the array and adds 1 to the integer.
A simple large number of additions, traversing each bit of the array, processing the carry, and if there is a carry at the end, insert 1 in front of the array.
Time complexity: O (N)
Space complexity: O (1)
1 class Solution2 {3 Public:4 Vector<int> PlusOne(Vector<int> &digits)5 {6 int C = 1; //Make carry ID initial value is 17 for(int I = digits.size() - 1; I >= 0; -- I)8 {9 //continuous handling of roundingTen int a = digits[I] + C; One digits[I] = a % Ten; A C = a / Ten; - } - //If there is a final rounding, insert 1 at the top of the array the if(C == 1) - digits.Insert(digits.begin(), 1); - - return digits; + } - };
Of course, because this problem is a relatively special large number of processing, only from the low start all is 9, will continue to produce a carry, and the number after rounding is 0. When and only if the number is all 9, it will be more in and out of 1, when the highest bit is 1, all the other bits are all 0 (due to the extra 1 bits, so you need to add 1 0 at the end).
1 class Solution2 {3 Public:4 Vector<int> PlusOne(Vector<int> &digits)5 {6 //From back to front, hit the first one not 9 to add 1, and then return to7 for(int I = digits.size() - 1; I >= 0; -- I)8 {9 if(digits[I] == 9)Ten digits[I] = 0; One Else A { - ++ digits[I]; - return digits; the } - } - //Top bit to 1, and then add another 0 - digits[0] = 1; + digits.push_back(0); - return digits; + } A };
Reprint please indicate source: Leetcode---66. Plus One
Leetcode---66. Plus One