LeetCode 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.

解决:

public class Solution {
    public int[] plusOne(int[] arr) {
        if(arr[arr.length - 1] != 9)
        {
                arr[arr.length - 1] += 1;
                return arr;
        }
        else
        {
            for(int index =arr.length - 1;index >= 0;index--)
            {

                if(arr[index] != 9)
                {
                    arr[index] += 1;
                    for(int i = index+1;i<arr.length;i++)
                        arr[i] = 0;

                    return arr;
                }
                    if(index == 0)
                {
                    int [] res = new int[arr.length+1];
                    for(int j = arr.length;j>=1;j--)
                    {
                        res[j] = 0;
                    }
                    res[0] = 1;
                    return res;
                }
            }
        }
        return arr;
    }
}

你可能感兴趣的:(LeetCode)