Saturday, June 27, 2015

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.
Have you met this question in a real interview?
Yes

Example
Given [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
        int n = digits.length;
        int[] res = Arrays.copyOf(digits, n);
        int carry = 1;
        for(int i = n - 1; i >= 0 && carry > 0; i--){
            res[i] = (digits[i] + carry) % 10;
            carry = (digits[i] + carry) / 10;
        }
        if(carry == 1){
            int[] result = new int[n+1];
            result[0]  = carry;
            System.arraycopy(res, 0, result, 1, n);
            
            return result;
        } 
        
        return res;
    }
}

No comments:

Post a Comment