[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;
}
};
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] 【数组】 66. Plus One
- 2018.3.12 leetcode打卡 #66 plus one
- [LeetCode]Plus One 优化
- Leetcode-66. Plus One
- leetcode 066 —— Plus One
- leetcode - Plus One
- [leetcode-66]plus one(java)
- [LeetCode]66. Plus One
- leetcode66.[Array] Plus One
- leetcode刷题记录-66. Plus One
- 【leetcode】plus One
- leetcode:Plus One
- LeetCode_Plus One
- leetcode挨个儿刷150507(7):Plus One
- Plus One - LeetCode
- leetCode 66. Plus One 数组
- Leetcode: Plus One
- Leetcode学习(29)—— Plus One
- leetcode[66]Plus One
- Leetcode 第66题 Plus One