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.

 

将一个整型数组当成一个整数,将该数加一后返回所得新的数组。

所要考虑的是进位和溢出问题,和Add Binary这道题类似,从低位逐位和进位相加,直至不产生进位为止,假若最高位产生进位,则组要new一个新的数组,size+1,并将新数组第一位置1,后面接上刚刚加完1的数组。

完整代码:

public class Solution {
    public int[] plusOne(int[] digits) {
        int size = digits.length;
        int carry = 1;
        for(int i=size-1;i>=0;i--){
            int sum = digits[i]+carry;
            if(sum>=10){
                carry = 1;
                digits[i] = sum-10;
            }
            else{
                carry = 0;
                digits[i] = sum;
                break;
            }
        }
        if(carry==1){
            int[] re = new int[size+1];
            re[0] = 1;
            for(int j = 0;j<size;j++){
                re[j+1] = digits[j];
            }
            return re;
        }
        return digits;
    }
}

 

转载于:https://www.cnblogs.com/mrpod2g/p/4273239.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值