LeetCode做题笔记 - 66

第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.

题目(中文)
给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

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)时间。
C++代码如下:

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;
    }
};

猜你喜欢

转载自www.cnblogs.com/xia-weiwen/p/10544522.html
66