letecode [66] - Plus One
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
题目大意:
给定一个非空数组,元素为0-9的数字,整个数组表示一个”整数“。对”整数“进行加一操作,返回该”整数“加一后的值,同样用数组表示。
理解:
主要是考虑进位问题,从数组尾部数字开始判断,若该元素digits[i] 等于9,则应进位(即digits[i] = 0,前一位加1),否则digits[i] = digits[i] + 1.
但需要特殊考虑最高位,若最高位为9,则扩充数组大小加1,再同理进行进位,最高位值为1.
代码C++:
class Solution { public: vector<int> plusOne(vector<int>& digits) { int n = digits.size(); vector<int> plusVec; int i; for (i = n - 1;i >= 0;--i) { if (digits[i] == 9) { digits[i] = 0; if (i == 0) { digits.push_back(0); for (i = n;i > 0;--i) { digits[i] = digits[i - 1]; } digits[0] = 1; } continue; } else { ++digits[i]; break; } } return digits; } };
运行结果:
执行用时 : 0 ms 内存消耗 : 8.6 MB