您的位置:首页 > 其它

[leetcode] Plus One

2014-07-20 11:14 141 查看
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.

思路:将加一的结果先逆序存在vector中,最高位进位如果为1则vector中再push_back一个1,然后将vector反转即得到结果

代码:

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