题目:加一(难度:简单)
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.git
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.spa
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.
思路
根据加法原理,加1加在最低位(个位)上。若是不进位,则只需将最低位加1。若是进位,则说明最低位是9,那么加上1后,最低位为0,而后考虑高一位(十位)的状况。若是高一位不进位,那么加1后结束,若是进位则必然本来是9,进位后变为0,继续向高一位进位。 所以,只须要从最低位开始,向高位遍历,若是不发生进位,则能够直接结束。 可是,若是一直到最高位,仍然有进位,怎么办?应该是最高位变0,并新增更高的一位,且为1。考虑到是vector,若是要在最开头加上一个元素,则须要消耗O(n)时间,确定尽可能避免这样的操做。仔细回想,对任意一位来讲,只有本来是9的状况下,才可能出现进位。所以,若是到最高位仍然须要进位,则说明本来的每一位都是9,而加1后,每一位都变为了0,只有多出来的最高位是1。因此,对这种特殊状况,只须要将数组的第一个元素设为1,而后最后添加一个0便可,只须要消耗O(1)时间。code
代码
class Solution { public: vector<int> plusOne(vector<int>& digits) { auto it = digits.end()-1; *it = (*it)+1; // 最低位加1 for (; it > digits.begin(); --it) // 从后向前遍历 { if (*it == 10) // 须要进位 { *it = 0; *(it-1) += 1; } else // 不进位,直接结束 { return digits; } } if (*it == 10) // 最高位进1,说明本来全部位都是9 { // 最高位置1,最后添0 *it = 1; digits.push_back(0); } return digits; } };