问题描述
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.
思路分析
给出一个用非空数组表示的整数,要求计算这个整数加一的结果。
问题的关键在于进位,如果最高位是9的话需要升一位,只有 999……99 这样的情况才会出现,正常情况还是从最后一位看起,逢9变0,非9加1即可。进位一定出现在循环结束之后,只需要看数组中的第一个元素有没有变成0即可。
代码
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
for(int i = n-1; i > -1; i--){
if (digits[i] == 9 )
digits[i] = 0;
else{
digits[i] += 1;
break;
}
}
if (digits[0] == 0){
digits[0] = 1;
digits.push_back(0);
}
return digits;
}
};
时间复杂度:O(n)
反思
思考了很久,主要是对于进位的处理没有想清楚,还是要想清楚边界条件,以及在对问题关键的把握要准确。