[Leetcode 4] 66 Plus One

Problem:

Given a number represented as an array of digits, plus one to the number.

 

Analysis:

The given array represents number from the greatest position to least position, so addition must start from the end of the array; 

When adding 1 to the number, there're two situations: 1. the digit is 9, then we need to set it to 0 and continue add to the next position; 2. the digit is not 9, then we add 1 to this digit and directly exit;

One more thing to consider is if all the digits are 9 (e.g. 9, 99, 999, 99999), after adding 1 the result has one more space (e.g. 10, 100, 1000, 100000); we must create a new space to contain the result;

 The time complexity in worst case is 2n, in best cast is 1, in general is O(n), the space complexity is O(n)

 

Code:

public class Solution {
    public int[] plusOne(int[] digits) {
        // Start typing your Java solution below
        // DO NOT write main() function
        //if (digits.length == 0) return 0;
        
        int i;
        for (i=digits.length-1; i>=0; --i) {
            if (digits[i] != 9) {
                digits[i] += 1;
                break;
            } else {
                digits[i] = 0;
            }
        }
        
        if (i < 0) {
            int[] newdigits = new int[digits.length+1];
            newdigits[0] = 1;
            for (int j=0; j<digits.length; j++)
                newdigits[j+1] = digits[j];
                
            return newdigits;
        } else
            return digits;
    }
}

 

Attention:

To new an primitive type array, use new Int[length]  rather than Int(length)

Can use System.arraycopy(src, pos, des, pos, len) to finish the copy process

 

posted on 2013-04-06 14:28  freeneng  阅读(332)  评论(0编辑  收藏  举报

导航