Plus One


Description:

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.


Solution

Simulation of behavior of add carry.

public class Solution {
    public int[] plusOne(int[] digits) {
        int one = 1, sum = 0, i, j;
        for (i = 0; i < digits.length; i ++) {
            if (digits[i] != 9)  break;
        }
        if(i == digits.length) {
            int[] res = new int[digits.length+1];
            res[0] = 1;
            return res;
        }
        else {
            for(j = digits.length - 1; j >= 0; j --) {
                sum = digits[j] + one;
                one = sum / 10;
                digits[j] = sum % 10;
            }
            return digits;
        }
    }
}

results matching ""

    No results matching ""