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.

链接:  http://leetcode.com/problems/plus-one/

题解:

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {

    public int[] plusOne(int[] digits) {

        int carry = 1;

        for(int i = digits.length - 1; i >= 0; i --){

            int curValue = digits[i];

            digits[i] = (curValue + carry) % 10;

            carry = (curValue + carry) >= 10 ? 1 : 0;

        }

        

        if(carry == 1){

            int[] result = new int[digits.length + 1];

            result[0] = 1;

            for(int i = 1; i < result.length; i ++){

                result[i] = digits[i - 1];

            }

            return result;

        } else 

            return digits;

    }

}

 

测试:

你可能感兴趣的:(one)