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之后的结果(仍然用数组表示)。
题解
这个比较简单,稍微需要注意的是当加一之后整个数进位了,需要扩大数组长度。
cpp用vector的话直接使用 arr.insert(arr.begin(),
1);
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int carry=1;
for(int i=digits.size()-1;i>=0;i--)
{
int temp=digits[i]+carry;
digits[i]=temp%10;
if(temp>9)
carry=1;
else
{
carry=0;
break;
}
}
if(carry==1)
digits.insert(digits.begin(),1);
return digits;
}
};