美文网首页
算法13 Plus One

算法13 Plus One

作者: holmes000 | 来源:发表于2017-11-12 22:26 被阅读0次

题目:给一个用数组表示的非负整数,加一并返回。
假设数组除了 0 本身不会零打头(不会有 01,007 这样的数组)。
高位在数组的前面。

思路:遍历数组的每位,同时判断是否要进位,如果最后还有进位,则在数组最前面在插入1即可。

代码:

public int[] plusOne(int[] digits){
    int n = digits.length;
    for (int i = n-1;i >= 0;i--){
       //若小于9,则加一,跳出循环返回
        if (digits[i] < 9){
            digits[i]++;
            return digits;
        }
        digits[i] = 0;
    }
    //说明前面都是9,所以添加一位,设成1
    int[] newDigits = new int[n+1];
    newDigits[0] = 1;
    return newDigits;
}

相关文章

  • 算法13 Plus One

    题目:给一个用数组表示的非负整数,加一并返回。假设数组除了 0 本身不会零打头(不会有 01,007 这样的数组)...

  • 每日算法:plus one

    题目:将一个不为0的数 拆分成一个数组,然后在数组最后一项加一。若大于10进位若小于直接返回

  • LeetCode 66-70

    66. Plus One[https://leetcode-cn.com/problems/plus-one/] ...

  • 66. Plus One

    66. Plus One 题目:https://leetcode.com/problems/plus-one/ 难...

  • Plus One

    https://leetcode.com/problems/plus-one/description/ 思路 反向...

  • Plus One

  • one plus

    Easy, Math Question 一个数以digit序列的形式给出,加一返回对应digit序列 Notes ...

  • Plus One

    Given a non-negative number represented as an array of di...

  • plus one

    question: answer: 之前蠢了,打印数组用Arrays.toString()方便很多直接在Syste...

  • Plus one

    Given a non-negative number represented as an array of di...

网友评论

      本文标题:算法13 Plus One

      本文链接:https://www.haomeiwen.com/subject/oeoomxtx.html