2013.12.22 03:37
Given a number represented as an array of digits, plus one to the number.
Solution:
This problem seems quite easy, right? See if you can AC with one shot.
Here're some good test cases for you:
0 + 1 = 1
1 + 1 = 2
34 + 1 = 35
99 + 1 = 100
Note that we write the number "100" in the order '1','0','0', it's stored as ['1', '0', '0']. Don't make it 001.
Time compelxity is O(n), where n is the length of the string.Space compelxity is O(1).
Accepted code:
1 // 3WA, 1AC 2 class Solution { 3 public: 4 vector<int> plusOne(vector<int> &digits) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 8 int i, len; 9 len = digits.size(); 10 11 if(len <= 0){ 12 return digits; 13 } 14 15 // 1WA here, add 1 at the wrong position, you FOOL!!! 16 ++digits[len - 1]; 17 // 1WA here, reversed order.. 18 for(i = len - 1; i > 0; --i){ 19 digits[i - 1] += digits[i] / 10; 20 digits[i] %= 10; 21 } 22 // 1WA here, carry propagation here neglected.. 23 if(digits[0] >= 10){ 24 int tmp = digits[0] / 10; 25 digits[0] %= 10; 26 digits.push_back(0); 27 for(i = len; i > 0; --i){ 28 digits[i] = digits[i - 1]; 29 } 30 digits[0] = tmp; 31 } 32 33 return digits; 34 } 35 };