[leetcode]66Plus One

时间:2017-07-28 18:11:45   收藏:0   阅读:197
/**
 * 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;
        }
    }
}

 

原文:http://www.cnblogs.com/stAr-1/p/7251670.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!