题目:
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.
一个整数按位存在一个数组中array[0]为最高位
代码:
class Solution { public: vector<int> plusOne(vector<int>& digits) { int size = digits.size(); if (digits[size - 1] != 9) { digits[size - 1]++; return digits; } else { for (int i = size - 1; i >= 0; --i) { if (++digits[i] > 9) { digits[i] = 0; } else break; } if (digits[0] == 0) { digits[0] = 1; digits.push_back(0); } } return digits; } };
本文介绍了一种在C++中实现数组表示的非负数加一的方法。通过检查数组的每一位,从最低位开始,如果遇到9则进位并重置该位为0,否则直接加一。特别地,当最高位为9且需要进位时,会在数组头部插入1,并在末尾添加0以保持数组的完整性。
561

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



