Plus One
Des
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.
分析
本题的意思是用一个数组给出一个数字,给这个数字加1,最后还返回一个数组。其实就是实现加法器。
需要注意的是9只有1位,加1后将变成两位。还需注意 vector< int > 没有push_front()方法,所以前边的逆序是有必要的。
Code
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> ret(digits);
reverse(ret.begin(), ret.end());
int flag = 1;
for(int i = 0; i < ret.size(); i++)
{
ret[i] += flag;
flag = ret[i] / 10;
ret[i] %= 10;
}
if (flag == 1)
ret.push_back(1);
reverse(ret.begin(), ret.end());
return ret;
}
};