Skip to content

Instantly share code, notes, and snippets.

@walkingtospace
Created August 29, 2014 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkingtospace/970b248b13d96803d65e to your computer and use it in GitHub Desktop.
Save walkingtospace/970b248b13d96803d65e to your computer and use it in GitHub Desktop.
plus-one
https://oj.leetcode.com/problems/plus-one/
/*
digit binaoperation은 언제나 carry 처리/자릿수 변경이 관건
맨 뒷자리부터 1씩 더해나가면서 carry 처리.
O(n)
carry 관련 문제는 언제나 loop끝나고 남은 carry를 처리해주는 것을 잊지 말것
001
111
101
*/
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
vector<int> res;
int carry = 1; //plus one
for(vector<int>::reverse_iterator it = digits.rbegin() ; it != digits.rend() ; ++it) {
if(*it == 9) {
if(carry == 1) {
res.push_back(0);
carry = 1;
} else {
res.push_back(9);
}
} else {
res.push_back(*it+carry);
carry = 0;
}
}
if(carry == 1) {
res.push_back(1);
}
reverse(res.begin(),res.end());
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment