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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值