Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
思路:这个问题很简单,和小学学的加法很想,最重要的是最后,如果进位是1,就要增加数组位数,用push_back(),然后把最后一项和第一项换一下位置就行了,代码如下:
1 class Solution { 2 public: 3 vector<int> plusOne(vector<int> &digits) { 4 int len=digits.size(); 5 int cm=0; 6 digits[len-1]=digits[len-1]+1; 7 if(digits[len-1]>=10) 8 { 9 cm=1; 10 digits[len-1]-=10; 11 } 12 for(int i=len-2;i>=0;i--) 13 { 14 if(cm==0) break; 15 else 16 { 17 digits[i]+=cm; 18 if(digits[i]>=10) 19 { 20 digits[i]-=10; 21 cm=1; 22 } 23 else cm=0; 24 } 25 } 26 if(1==cm) 27 { 28 digits.push_back(cm); 29 swap(digits[0],digits[len]); 30 } 31 return digits; 32 } 33 };