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.
The logic is very clear. Plus one.
vector<int> plusOne(vector<int>& digits) {
int size = digits.size();
digits[size - 1] += 1; // lowest bit is at the end.
for(int j = size - 1; j >= 1 && digits[j] == 10; j--) {
digits[j] = digits[j] % 10;
digits[j-1] += 1;
}
if(digits[0] == 10) {
digits[0] = 0;
digits.insert(digits.begin(), 1);
}
return digits;
}
本文介绍了一种将非负整数表示为数字数组,并在此基础上实现加一操作的算法。该算法从数组最低位开始逐位处理进位,直至最高位。通过C++代码实现了这一逻辑,展示了如何有效地处理数组中每一位数字的加一运算。
592

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



