LeetCode 66. Plus One

本文介绍了一种在数组上直接进行加一操作的算法,避免了将数组转换为长整型数字时可能出现的问题,通过逐位进位处理,实现了数组表示的非负整数加一的功能。

问题:给数组加一

具体为:给定的数字是用数组表示的,如[1,2,3]表示的数是123,所以123+1=124,再输出数组[1,2,4]

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.

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

思路:

最开始有想过先把数组转为数字,但是考虑到之前这么做过然后出现太长的数字时没法处理,所以直接在数组上进行的操作

最开始只在末尾+1,如果末尾为9,则末尾变为末尾-9,且指定进位标记flag=1,对数组从后到前进行进位,直到遇到不需要进位的时候为止

注意:需要考虑加一之后数字变多一位的可能,如999+1=1000,此时无法在原数组上进行修改,所以需要新建一个数组

class Solution {
    public int[] plusOne(int[] digits) {
        int len = digits.length;
        if(len==0){
            return digits;
        }
        if(digits[len-1]+1<10) {
        	digits[len-1] ++;
        	return digits;
        }
        
        digits[len-1] = digits[len-1]-9;
        int flag = 1;
       
        for(int i=len-2;i>=0;i--){
            if(digits[i] + flag <10){
                digits[i] = digits[i] + flag;
                flag = 0;
                break;
            }
            if(digits[i] + flag+1>=10){
                digits[i] = digits[i]-9;
            }
        }
        
        if(flag==1){
        	digits = add1first(digits);
        }
        return digits;
    }
    
    // 新建一个数组,前面为1,后面为加1之后的结果
    public static int[] add1first(int[] nums){
        int len = nums.length;
        int[] new_nums = new int[len+1];
        new_nums[0] = 1;
        for(int i=1;i<len+1;i++){
           new_nums[i] = nums[i-1] ;
        }
        return new_nums;
    }
}

结果:

Runtime: 0 ms, faster than 100.00% 

Memory Usage: 37.3 MB, less than 19.04% 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值