Leetcode P0066"Plus One" 题解

2020/08/28 Leetcode

博文中会简要介绍Leetcode P0066题目分析及解题思路。

“Plus One”是一道比较简单的题目,主要考察在于对进位的处理。

Given a non-empty array of digits representing a non-negative integer, increment 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 contains a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

以下是Java的题解代码实现。

class Solution {
    public int[] plusOne(int[] digits) {
        int resLen = digits.length;
        
        digits[resLen-1] += 1;
        int increment = digits[resLen-1]/10;
        digits[resLen-1] %= 10;
        if (increment == 0)
            return digits;
        
        int[] result = new int[resLen+1];
        for (int itr=resLen-2; itr>=0; --itr) {
            int sum = digits[itr]+increment;
            result[itr+1] = sum%10;
            increment = sum/10;
            digits[itr] = result[itr+1];
            
            if (increment == 0)
                return digits;
        }
        
        result[0] = increment;
        return result;
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int resLen = digits.size();
        
        digits[resLen-1] += 1;
        int increment = digits[resLen-1]/10;
        digits[resLen-1] %= 10;
        if (increment == 0)
            return digits;
        
        vector<int> result(resLen+1, 0);
        for (int itr=resLen-2; itr>=0; --itr) {
            int sum = digits[itr]+increment;
            result[itr+1] = sum%10;
            increment = sum/10;
            digits[itr] = result[itr+1];
            
            if (increment == 0)
                return digits;
        }
        
        result[0] = increment;
        return result;
    }
};

Search

    Table of Contents