Leetcode刷题114-66. 加一(C++最简单实现详细解法!!!)

Come from : [https://leetcode-cn.com/problems/plus-one/submissions/]

1.Question

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.

2.Answer

easy类型题目。。。(但我还是遇到了不小麻烦)。
我的思路:

首先读题,数组是一个非空(non-empty array)的,因此不需要特殊处理数组长度为0的情况。
其次本题考察的重点,就是如何处理 数字 9 的这个情况(因为要 进1 嘛)。。。

AC代码如下:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        for(int i = digits.size()-1; i >=0 ; --i)  //反向遍历
        {
            if(digits[i] == 9)             //有进位 即继续遍历
            {
                digits[i] = 0;
            }
            else
            {
                ++digits[i];                //没有就退出循环
                break;
            }
        }
        
        if(digits[0] == 0)              //当首位 为 9 的时候,按照上面的 步骤 digits[0] 变为 0 了,此时需要 在前面加个 1
        {
            digits.insert(digits.begin(), 1); //向迭代器(此处为digits.begin())的 前面一个位置 加 一个元素,此时元素 为 1
        }
        return digits;
    }
};

3.大神解答

速度排名第一(我的速度排名第一,惊不惊喜,意不意外,哈哈哈)。

4.我的收获

fighting。。。

2019/7/4 胡云层 于南京 114

猜你喜欢

转载自blog.csdn.net/qq_40858438/article/details/94655718