题目描述:
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
一个数以数组的形式存储,要求计算它加一之后的结果。其实就是模拟竖式加法,注意进位。
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int i=digits.size()-1;
while(true)
{
if(digits[i]<9)
{
digits[i]++;
break;
}
else
{
digits[i]=0;
i--;
if(i==-1)
{
digits.insert(digits.begin(),1);
break;
}
}
}
return digits;
}
};
本文介绍了一个简单的算法问题——给定一个表示非负整数的数字数组,在此基础上加一并返回新的数组。通过示例说明了如何进行操作,并提供了一个C++实现方案,重点在于如何处理进位。
303

被折叠的 条评论
为什么被折叠?



