Created
December 25, 2013 06:59
-
-
Save xswang/8120851 to your computer and use it in GitHub Desktop.
leetcode Plus One 各位加1,注意进位,后面的就直接是进位与原始的数相加了。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> plusOne(vector<int> &digits) { | |
int t = digits.size(); | |
reverse(digits.begin(), digits.end()); | |
int q = 0; | |
int sum = 0; | |
sum = digits[0] + 1;//第一位加1 | |
q = sum/10;//取得进位 | |
sum %= 10;//取余数。 | |
digits[0] = sum;//第一位等于余数 | |
for(int j = 1; j < t; j++){ | |
sum = digits[j] + q;//从第一位开始,加上之前的进位(如果有进位的话) | |
q = sum/10;// | |
sum = sum % 10; | |
digits[j] = sum; | |
} | |
if(q != 0) digits.push_back(q); | |
reverse(digits.begin(), digits.end()); | |
return digits; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment