Plus One

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.


尝试翻译

给定一个以数组表示的非负数,向该数字加一,并将该数字权重最大的数放在数组的第一位

标签:数组,数学

其实就是一个高精度的加法 ||

我的提交

public int[] PlusOne(int[] digits) {
    List<int> list = new List<int>(digits);

        int carry = 1;
        for(int i=list.Count-1;i>=0;i--)
        {
            int temp = list[i] + carry;
            carry = temp / 10;
            list[i] = temp % 10;
        }

        if(carry>0)
        {
            list.Insert(0, 1);
        }


        return list.ToArray();
}

注意事项:

  • 使用carry存储进位,因本题加一,所以carry初始化为1
  • (数组长度)次循环(必须从数组右端开始运算 <- 运算过程的低位):
    • 使用temp存储A[i]与carry相加的结果,不能将A[i]+carry的结果直接放入A[i],因为进位carry与运算后的A[i]需根据temp确定,以防相加后的结果大于10
    • 此次高精度加法为十进制,进位为商carry=temp/10(只有10/10=1;得数为余数(小于10的数除以10的余数等于self)A[i]=temp%10
    • 需确定最高位运算后,是否有进位产生,若有,carry必为1,此时需将1放在数组的第一位

P.S:此解法可能由于参考了其他解法而导致有相似之处,感谢他们的分享!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值