Plus One

Problem: 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.


public class Solution {
    public int[] plusOne(int[] digits) {
        if (digits.length == 0) return digits;
        
        int toAdd = 1;
        
        for (int i = digits.length-1; i >= 0; i--) {
            if (digits[i] + toAdd > 9) {
                toAdd = 1;
                digits[i] = 0;
            }else{
                digits[i] += toAdd;
                toAdd = 0;
                break;
            }
        }
        
        if (digits[0] == 0) {
            int[] temp = new int[digits.length + 1];
            temp[0] = 1;
            for (int i = 0; i < digits.length; i++) {
                temp[i+1] = digits[i];
            }
            digits = temp;
        }
        
        return digits;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s