您的位置:首页 > 编程语言 > C语言/C++

leetcode #66 in cpp

2016-05-31 01:48 351 查看
Solution: 

1.start from the tail of the input, and keep adding 1 until we reach the head of the input or the digit + 1 is less than 10. 

2.check if the head >= 10. If so insert an extra 1 to the input.

Code:

class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int i = digits.size() - 1;
int carry = 1;
while(carry && i >=0){
digits[i]+=carry;
if(digits[i] >=10){
carry = 1;
digits[i]%=10;
}else carry = 0;
i--;
}
if(carry){
digits.insert(digits.begin(), 1);
}
return digits;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode