当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

[Leetcode] Plus One 加一

作者:小梦 来源: 网络 时间: 2024-01-28 阅读:

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.

记录长度法

复杂度

时间 O(N) 空间 O(1)

思路

简单的加法运算。这里需要注意的是,数字的最高位的下标是0,最低位下标是length-1,所以我们要从后向前模拟加法。不过这里有个小技巧,因为我们只要加1,所以不用完全模拟加法的所有规则:一个数如果不是9,那加1以后不会对其他位产生影响。根据这个思路,我们先把末尾所有连续的9置0,然后对从后往前第一个不是9的数加1就行了。如果越界的话,说明原数全是9,那就要建个新数组存放结果。

注意

System.arraycopy(src, 0, dst, 0, length) 可以用来高效拷贝数组

代码

public class Solution {    public int[] plusOne(int[] digits) {        int i = digits.length - 1;        // 从后向前把所有连续9置0,直到不是9        while(i >= 0 && digits[i] == 9){digits[i] = 0;i--;        }        // 如果越界,则拷贝一个新数组并在最前面置1        if(i < 0){int[] res = new int[digits.length + 1];System.arraycopy(digits, 0, res, 1, digits.length);res[0] = 1;return res;        } else {        // 否则,将第一个不是9的数字加1就行了digits[i] += 1;return digits;        }    }}

网友最爱