java 66.加上One.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 66.加上One.java相关的知识,希望对你有一定的参考价值。


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

"""
"""
TESTCASES:

Input:
[0]
[1,2,3]
[1,2,9]
[9,9]

Output:
[1]
[1,2,4]
[1,3,0]
[1,0,0]
"""
class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        
        res = [];
        flag = 1;
        for i in range(len(digits) - 1, -1 ,-1):
            temp = (digits[i] + flag) / 10;
            res.append((digits[i] + flag) % 10);
            flag = 1 if temp else 0;
        
        if flag == 1:
            res.append(1);
        
        return res[::-1];
public class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null || digits.length < 1) return digits;
        int len = digits.length;
        for (int i = len - 1; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            digits[i] = 0;
        }
        
        int[] newNumber = new int[len + 1];
        newNumber[0] = 1;
        return newNumber;
    }
}

以上是关于java 66.加上One.java的主要内容,如果未能解决你的问题,请参考以下文章

java 66.加上One.java

java 66.加上One.java

java 66.加上One.java

java 66.加上One.java

java FragmentList_One.java

Java连载66-数组的两种初始化方式