题目描述: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.
分析:此题是将一个非负整数用一个vector<int>来存放,要求实现对该数加1后输出结果向量,这不是很简单的加法么?小学生都会算。
此题的关键是处理进位,用一个循环,从向量末尾向前运算,最后一位加1,如果进位为0,则说明不用再往前运算了,直接退出循环,返回结果向量即可;如果进位为1,继续向前按照相同的方式计算。循环结束后,如果进位为1,需将其添加到结果向量的头部。
以下是c++实现的代码,添加了一个打印函数用于测试:
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
void output(vector<int> digits)
{
for(vector<int>::iterator itr = digits.begin(); itr != digits.end(); itr++)
cout << *itr << " ";
cout << endl;
}
vector<int> plusOne(vector<int> &digits) {
vector<int>::size_type ix;
vector<int> result;
int push = 1; /* 将首次末位加1当作进位1 */
int t = 0;
for(ix = digits.size()-1; ix != -1; ix -- )
{
t = push;
push = (digits[ix] + t)/10;
digits[ix] = (digits[ix] + t)%10;
if(push == 0) /* 当进位为0,则退出循环,返回结果,如果此处不判断进位,则会超时 */
return digits;
}
result.push_back(push); /* 最后的进位为1,需将其加入到结果向量头部 */
for(ix = 0; ix != digits.size(); ix++ )
{
result.push_back(digits[ix]);
}
return result;
}
};
int main ()
{
Solution solution;
vector<int> digits;
digits.push_back(9);
digits.push_back(9);
solution.output( solution.plusOne(digits));
system("pause");
return 0;
}