Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
s思路:
1. 简单题。直接加。
//方法1:先reverse,加1,再reverse back.用标志位carry
class Solution {
public:
void reverse(vector<int>& digits){
int l=0,r=digits.size()-1;
while(l<r){
swap(digits[l],digits[r]);
l++;r--;
}
}
vector<int> plusOne(vector<int>& digits) {
//
reverse(digits);
int carry=1;
for(int i=0;i<digits.size()&&carry==1;i++){
if(digits[i]==9){
digits[i]=0;
}else{
digits[i]++;
carry=0;
}
}
if(carry) digits.push_back(1);
reverse(digits);
return digits;
}
};
//方法2:不reverse,直接加
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
//
int carry=1;
for(int i=digits.size()-1;i>=0&&carry==1;i--){
if(digits[i]==9){
digits[i]=0;
}else{
digits[i]++;
carry=0;
}
}
if(carry) digits.insert(digits.begin(),1);
return digits;
}
};