[leetcode]66Plus One

/**
 * Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

 You may assume the integer do not contain any leading zero, except the number 0 itself.

 The digits are stored such that the most significant digit is at the head of the list.
 */
/*
* 从最后一位到第二位倒着遍历,重写每位的数据,如果遇到不进位的情况,直接返回数据
* 由于第一位关系到是否需要新建数组,所以单独判断,只要运行完循环,肯定是有进位的,因为如果没有的话就返回了
* 所以不需要设置进位标志*/
public class Q66PlusOne {
    public int[] plusOne(int[] digits) {
        int l = digits.length;
        for (int i = l-1; i >=1 ; i--) {
            int cur = digits[i] + 1;
            digits[i] = cur % 10;
            if (cur / 10 == 0)
                return digits;
        }
        if (digits[0] < 9)
        {
            digits[0] += 1;
            return digits;
        }
        else
        {
            int[] res = new int[l+1];
            res[0] = 1;
            for (int i = l;i > 0;i-- )
            {
                res[i] = 0;
            }
            return res;
        }
    }
}

 

posted @ 2017-07-28 17:49  stAr_1  阅读(165)  评论(0编辑  收藏  举报