算法分析与设计作业题
作业来源
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 carry = 1;
for (int i = digits.size() - 1; i >= 0; i--)
{
auto sum = digits[i] + carry;
digits[i] = sum % 10;
carry = sum / 10;
}
if (carry > 0)
{
digits.insert(digits.begin(), carry);
}
return digits;
}
};
本文探讨了一个常见的算法题目,即给定一个表示非负整数的非空数字数组,在此基础上加一并返回结果。文章详细解析了算法实现,包括进位处理和特殊情况讨论,展示了如何通过迭代方式解决该问题。
1719

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



