[Leetcode] PlusOne

问题描述 Given a number represented as an array of digits, plus one to the number.

代码

public class Solution {
    public int[] plusOne(int[] digits) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int len = digits.length;
        int pivot = len -1;
        if(digits[pivot]<9){
            digits[pivot]++;
            
        }
        else {
        
            while(digits[pivot]==9 && pivot > 0 ){
                digits[pivot] = 0;
                pivot--;
            }
            if(pivot != 0 || digits[pivot] != 9 )
            digits[pivot]++;
            else {
                int [] digits_new = new int[len+1];
                digits_new[0] = 1;
                for(int i=1;i<=len;i++)
                digits_new[i] = 0;
                return digits_new;
            }
        }
        return digits;
    }
}
思路跟这篇差不多

你可能感兴趣的:([Leetcode] PlusOne)