Leetcode -- Plus One

https://oj.leetcode.com/problems/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)


Leetcode经常会出现这种题----休闲题,简单的让你充满自信而不被Median of two sorted arrays或者Scramble String这样的题给折磨晕。。。。

这题也是很简单的,注意进位就好。另外也注意一下代码里关于System.arraycopy()的运用:

    public int[] plusOne(int[] digits) {
        int next = 1;
        for(int i = digits.length - 1; i >= 0 && next == 1; i--){
            digits[i] += next;
            next = digits[i] / 10;
            digits[i] %= 10;
        }
        if(next == 1){
            int[] res = new int[digits.length + 1];
            System.arraycopy(digits, 0, res, 1, digits.length);//System.arraycopy(Object src, int srcpos, Object dest, int destpos, int length)
            res[0] = 1;
            return res;
        }else
            return digits;
    }

一旦出现了最高位进位的需要,就只能开一个新的空间来放答案了。注意一下System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

这个函数的实现是在底层native端的,比一个个拷贝复制要快速的多。

另外注意一下这个函数的参数,你会发现其实在Java里数组[]也是Object的一种继承。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值