Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 28, 2013 14:42
Show Gist options
  • Select an option

  • Save pdu/4656037 to your computer and use it in GitHub Desktop.

Select an option

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
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