Tuesday, February 4, 2014

Leetcode: Plus One

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

Solution:

public class Solution {
    public int[] plusOne(int[] digits) {
        boolean carryOn = true;
        for(int i= digits.length-1; carryOn && i>=0; i--)
        {
            digits[i]+=1;
            carryOn = digits[i]>9;
            digits[i] %=10;
        }
        
        if(carryOn)
        {
            int[] newDigits = new int[digits.length+1];
            newDigits[0]=1;
            for(int i=0; i<digits.length; i++)
                newDigits[i+1]=digits[i];
            return newDigits;
        }
        return digits;
    }
}

No comments :

Post a Comment