您的位置:首页 > 其它

[LeetCode] 66. Plus One

2016-07-19 03:25 381 查看


Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

解法一:

检查最后一位是不是9,不是9的话,末尾加1返回数字。如果是9,则该位变为0,并检查上位bit是不是为9,如果依然为9,说明需要继续向上进位,直至值不为9的bit。如果最高位的值最终是0的话,说明需要补上一个进位bit.
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
for(int i = n-1; i>=0; --i){
if (digits[i] == 9){
digits[i] = 0;
}else{
digits[i]+=1;
return digits;
}
}
if (digits.front()==0){
digits.insert(digits.begin(),1);
}
return digits;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  easy leetcode