leetcode - [66] Plus One

2020/07/22

问题描述

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.

数组形式+1

举个例子:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

解法1

Thanks @caikehe

先来看下示意图:

主要包含三种情况:

第一种,如: x = 25

数组的最后一位是5,加一后,仍小于等于9,所以直接快速返回26

第二种,如: x = 29

此时,数组的最后一位加一后变成0,那么进位仍是1,然后1 + 2 = 3 <= 9,所以直接返回30

第三种,如: x = 99

遍历完数组中的二位元素后,发现还没有结束,那么此时需要新创建一个长度+1的数组,

并且把第一位赋1即可,也就是100

来看下实现:

class Solution {
    public int[] plusOne(int[] digits) {
        
        int n = digits.length;
        int c = 1;
        for (int i = n - 1; i >= 0; i--){
            digits[i] += c;
            if (digits[i] <= 9){
                return digits;
            }
            digits[i] = 0;
        }
        // 99 -> 100
        int[] ans = new int[n + 1];
        ans[0] = 1;
        return ans;
    }
}

Enjoy it !


一位喜欢提问、尝试的程序员

(转载本站文章请注明作者和出处 姚屹晨-yaoyichen

Post Directory