题目:
Given a number represented as an array of digits, plus one to the number.
思路:
数组的遍历需要从右向左进行,然后结果存在临时数组中为从左向右。输出前遍历一半的数组将数组反序。代码:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> v;
int next = 1;
for(int i = digits.size() - 1; i >= 0 ; i--)
{
int tmp = digits[i] + next;
v.push_back(tmp%10);
next = tmp/10;
}
if(next != 0)
{
v.push_back(next);
}
for(int i = 0; i < v.size()/2; i++)
{
int t = v[i];
v[i] = v[v.size() - 1 - i];
v[v.size() - 1 - i] = t;
}
return v;
}
};