算法题目 :Plus One
算法题目描述:
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.
算法分析:
这道题目主要是说给定一个用数组表示的非负整数,在此基础上加1。
这就要求我们分析每一位是9还是非9:倘若最后一位是9,则就要求进位;再依次看前面的每一位是否为9,如果是,则在再重复前面的步骤。
我们可以用大于10的数求解每一位大小的方法来计算本位和进位,即用取模和整数除法来计算。
最后如果进位为1,则要求再加一位。
算法代码(C++):
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int jinwei = 1;
int cunchu;
for(int i = digits.size() - 1; i >= 0; i--)
{
cunchu = digits[i] + jinwei;
digits[i] = cunchu % 10;
jinwei = cunchu / 10;
}
//如果进位不为0,则添加一位最高位,最高位要加1
if(jinwei != 0)
digits.insert(digits.begin(), 1);
return digits;
}
};
性能分析: