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.
Subscribe to see which companies asked this question
思路解析:
本题不难理解。在题意上纠结了五分钟。其实就是一个数字,其中的每一位是数组中的每一个元素。
class Solution {
public:
vector<int> plusOne(vector<int>& digits)
{
if (digits[digits.size() - 1] != 9)
{
digits[digits.size() - 1] ++;
return digits;
}
else
{
digits[digits.size() - 1] = 0;
int carry = 1;
for (int i = digits.size() - 2; i >=0; i--)
{
if (digits[i] != 9)
{
digits[i]++;
return digits;
}
else
{
digits[i] = 0;
}
}
//都是9的情况
vector<int> res(digits.size() + 1, 0);
res[0] = 1;
return res;
}
}
};
本文讲解如何使用数组实现数字加一操作,详细解析算法过程,包括边界条件处理和进位逻辑。
592

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



