您的位置:首页 > 其它

LeetCode | Plus One(数组表示的数字加1)

2014-08-18 19:22 323 查看
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.
题目解析:
用数组表示的数字,将其+1,得到结果。跟Add Binary一样,加上后进位。但容器的话,插入要用insert函数。

class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int len = digits.size();
vector<int> res;
if(len == 0){
res.push_back(1);
return res;
}
int carry = 1;
for(int i = len-1;i >= 0;i--){
int sum = digits[i]+carry;  //先求总和再判断是否进位
if(sum>=10)
carry = 1;
else
carry = 0;
res.insert(res.begin(),sum%10); //在容器的指定位置插入元素
}
if(carry)
res.insert(res.begin(),1);
return res;
}
};


我是重新申请的一个来存储新值,也可以在原始数据基础上修改。

class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int i;
for(i = digits.size() - 1;i >= 0;--i){
if(digits[i] != 9){
++digits[i];
return digits;
}
else {
digits[i] = 0;
}
}
//各位全是9
if(i < 0) {
digits.insert(digits.begin(),1);
}
return digits;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐