Sunday, February 9, 2014

Plus One

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

Solution:
Basic implementation question.

public class Solution {
    public int[] plusOne(int[] digits) {
        if(digits.length == 0) return digits;
        int temp = 0;
        int carry = 0;
        for(int i = digits.length - 1; i >= 0; i--){
            temp = 0;
            if(i == digits.length - 1) temp = digits[i] + 1;
            else temp = digits[i] + carry;
            if(temp == 10){
                digits[i] = 0;
                carry = 1;
            }
            else{ 
                digits[i] = temp;
                carry = 0;
                break;
            }
        }
        // expand array
        if(carry == 1){
            int[] results = new int[digits.length+1];
            results[0] = 1;
            for(int i = 1; i < results.length; i++){
                results[i] = digits[i-1];   
            }
            return results;
        }
        return digits;
    }
}

No comments:

Post a Comment