Leetcode Plus One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.


解题思路:

先对原数组进行处理。从数组最后一位开始往前检查,如果当前数字是<9的,说明你加1无需进位,从循环跳出即可,如果当前数字等于9,说明加1涉及进位,且加1后当前数字应记为0,继续循环处理。

当对原数组处理完后,还需要判断当前第0位是不是已经变为0了,如果已经变为0了说明是类似99+1这种,需要进位。其他则不需要。

一般对数字进行操作的题都要考虑边界,尤其是溢出问题。


Java code:

public int[] plusOne(int[] digits) {int len = digits.length;
        for(int i=len-1; i>=0; i--){
            if(digits[i] < 9) {
                digits[i]++;
                break;
            }else{
                digits[i] = 0;
            }
        }
        
        int[] newdigits;
        if(digits[0] == 0){
            newdigits = new int[len+1];
            newdigits[0] = 1;
            for(int i = 1; i< newdigits.length;i++) {
                newdigits[i] = digits[i-1];
            }
            return newdigits;
        }
        return digits;
    }

Reference:

1. http://www.cnblogs.com/springfor/p/3888002.html

 

转载于:https://www.cnblogs.com/anne-vista/p/4827826.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值