Plus one

2017-01-05  本文已影响0人  Leonlong

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.
ExampleGiven [1,2,3]
which represents 123, return [1,2,4]
.
Given [9,9,9]
which represents 999, return [1,0,0,0]

比较简单的题,从尾到头遍历,然后如果有进位依次加一,最后在判断是否需要加一个数字到数组头。

public class Solution {
    /**
     * @param digits a number represented as an array of digits
     * @return the result
     */
    public int[] plusOne(int[] digits) {
        // Write your code here
        if(digits == null || digits.length < 1){
            return digits;
        }
        
        int adder = 1;
        for (int i = digits.length-1; i >= 0 && adder > 0; i--) {
            int sum  = digits[i] + adder;
            digits[i] = sum % 10;
            adder = sum / 10;
        }
        
        if(adder == 0){
            return digits;
        }
        
        int[] num = new int[digits.length + 1];
        num[0] = 1;
        for( int j = 1; j < digits.length; j++) {
            num[j] = digits[j-1];
        }
        return  num;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读