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

[LeetCode]66. Plus One

2016-04-16 23:00 666 查看

66. Plus One

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后的结果。这个从后往前遍历即可。

源码

class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int carry = 1;
int sum = 0;
for(int i = digits.size() - 1; i >= 0; i--){
sum = digits[i] + carry;
carry = sum / 10;
digits[i] = sum % 10;
}
//最后还有进位的话需要添加一位如,99+1 = 100
if(carry > 0) digits.insert(digits.begin(),carry);
return digits;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode plus one C++