超级简单的一道题,就是把一个整数加上一,只是这个整数是保存在vector里面的。
注意的是最高位存在第0个位置。
可是这个题这么简单,我还错,真是醉了!!!
不过,一边实习上班,一边抽代码运行的空隙里刷道题确实也是分心了,哎。
题目:
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.
先贴出来错误的代码,错误的认为了如果首位是9,就会进位这种情况,简直胡来!!!
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> result;
int size = digits.size();
if(size <= 0)
return result;
if(digits[0] == 9)
result.resize(size + 1);
else
result.resize(size);
vector<int> :: iterator vit=digits.end();
vit--;
int new_size = result.size();
int i = new_size - 1;
int add_one = 1;
while(vit != digits.begin())
{
result[i] = (*vit + add_one)%10;
add_one = (*vit + add_one)/10;
i--;
vit--;
}
result[i] = (*vit + add_one)%10;
i--;
add_one = (*vit + add_one)/10;
if(add_one == 1)
result[i] = add_one;
return result;
}
};
现在是正确的代码内容:
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> result;
int size = digits.size();
if(size <= 0)
return result;
stack<int> result_stack;
int add_one = 1;
vector<int> :: iterator vit=digits.end();
vit--;
while(vit != digits.begin())
{
result_stack.push( (*vit + add_one)%10 );
add_one = (*vit + add_one)/10;
vit--;
}
result_stack.push( (*vit + add_one)%10 );
add_one = (*vit + add_one)/10;
if(add_one == 1)
result_stack.push( (add_one)%10 );
while(!result_stack.empty())
{
result.push_back(result_stack.top());
result_stack.pop();
}
return result;
}
};
使用的数据结构是vector和stack,均需一次遍历,复杂度为O(n)。