首页 > 代码库 > [LeetCode] NO. 66 Plus One

[LeetCode] NO. 66 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.

 

[题目解析] 用一个数组表示一个非负数,然后进行加1的操作,数组第一位是最高位。题目比较简单,我们考虑只有某一位为9并且有进位的情况下,该位会变成0,然后进位,否则就直接该位进行+1操作即可。

当所有位都是9的特殊情况下,要特别处理一下,具体代码如下。

    

  public int[] plusOne(int[] digits) {        int flag = 1;        int len = digits.length;        int []ret = new int[len+1];        for(int i = len-1; i >= 0; i--){            if(digits[i] == 9){                digits[i] = 0;            }else{                digits[i]++;                return digits;            }        }        ret[0] = 1;        return ret;  }

  

[LeetCode] NO. 66 Plus One