Created
January 28, 2013 14:42
-
-
Save pdu/4656037 to your computer and use it in GitHub Desktop.
Given a number represented as an array of digits, plus one to the number. http://leetcode.com/onlinejudge#question_66
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 all9 = 1; | |
| for (int i = 0; i < digits.size(); ++i) | |
| if (digits[i] != 9) { | |
| all9 = 0; | |
| break; | |
| } | |
| int len = digits.size() + all9; | |
| vector<int> ret; | |
| ret.resize(len); | |
| int cur = len - 1; | |
| digits[ digits.size() - 1 ]++; | |
| for (int i = digits.size() - 1; i >= 0; --i) { | |
| if (digits[i] < 10) | |
| ret[cur--] = digits[i]; | |
| else { | |
| ret[cur--] = digits[i] - 10; | |
| if (i == 0) | |
| ret[cur] = 1; | |
| else | |
| digits[i - 1]++; | |
| } | |
| } | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment