Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 16, 2013 22:13
Show Gist options
  • Save zhoutuo/4968959 to your computer and use it in GitHub Desktop.
Save zhoutuo/4968959 to your computer and use it in GitHub Desktop.
Given a number represented as an array of digits, plus one to the number.
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
for(int i = 0; i < digits.size() / 2; ++i) {
swap(digits[i], digits[digits.size() - i - 1]);
}
int remainder = 1;
int index = 0;
while(remainder != 0) {
if(digits.size() == index) {
digits.push_back(0);
}
digits[index] += remainder;
if(digits[index] == 10) {
digits[index] = 0;
remainder = 1;
} else {
remainder = 0;
}
++index;
}
for(int i = 0; i < digits.size() / 2; ++i) {
swap(digits[i], digits[digits.size() - i - 1]);
}
return digits;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment