[LeetCode]第十一题 :数字+1

题目描述:

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.

题目解释:

给出一组非空数组,使这个数组组成的数字 + 1。

数字被存储,使得最重要的数字位于列表的头部,并且数组中的每个元素都包含一个数字。你可以假设整数不包含任何前导零,除了数字0本身。

题目解法:

1.我的解法:首先,创建一个新数组,新数组长度是原数组长度 + 1;将原数组放到新数组从下标1开始到最后的位置;新数组最后一个值 + 1;接着从后遍历新数组,如果说新数组当前下标的值大于9,那么当前下标这个值 - 10,当前下标的上一个位置的值+ 1,直到遍历完;最后判断新数组的开头,如果新数组0下标的值为0,说明没有进位,否则说明进了位。

class Solution {
    public int[] plusOne(int[] digits) {
        int[] result = new int[digits.length + 1];
        for(int i = 1;i< result.length;i++) {
            result[i] = digits[i - 1];
        }
        result[result.length -1] += 1;
        for(int i = result.length -1;i>=0;i--) {
            if(result[i] > 9) {
                result[i] = result[i] - 10;
                result[i - 1] += 1;
            } else break;
        }
        if(result[0] != 0) {
            return result;
        } else {
            int[] array = new int[digits.length];
            for(int i = 0;i<array.length;i++) {
                array[i] = result[i+1]; 
            }
            return array;
        }
    }
}

错误思路:

首先其实我想的是把int[]数组转成数字,然后这个数字进行 +1操作,最后再把这个数字转换成int数组。问题:数字超过取值范围。

class Solution {
    public int[] plusOne(int[] digits) {
        Integer number = 0;
        for(int i = digits.length - 1;i >= 0 ; i--){
            int temp = 1;
            for(int j = 0;j < digits.length - 1 - i;j++) {
                temp = temp * 10;
            }
            number += (digits[i] * temp);
        }
        number += 1;
        int length = 1;
        int temp = number;
        while((temp / 10) != 0) {
            temp = temp / 10;
            length++;
        }
        int[] result = new int[length];
        for(int i = length - 1; i >= 0;i--) {
            result[i] = number % 10;
            number = number/10;
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/80824096