思路:
逐数字相加,采用进位标志标记是否需要进位
代码:
class Solution {
public:
/**
* @param digits a number represented as an array of digits
* @return the result
*/
vector<int> plusOne(vector<int>& digits) {
// Write your code here
int len = digits.size(), tmp = 0, plus = 1;
for(int i = len - 1;i >= 0; --i){
tmp = digits[i] + plus;
digits[i] = tmp % 10;
plus = tmp / 10;
}// for
if(0 == plus)
return digits;
digits.push_back(0);
for(int i = len; i > 0; --i)
digits[i] = digits[i - 1];
digits[0] = 1;
return digits;
}
};
本文介绍了一种在C++中实现的数组加一算法。该算法通过遍历数组并逐位进行加一操作来实现,同时处理进位情况。文章详细展示了如何在遇到进位时更新数组元素,并在最高位发生进位时扩展数组。
486

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



