Featured TOP -leetcode face questions plus a question of programming to achieve -java

Description of the problem:
a non-negative integer given a non-empty array of integers represented by plus one on the basis of this number.

Most significant digit stored in the first array, each element of the array stores a number only.

You may assume that in addition to the integer 0, the integer does not begin with a zero.

Example 1:
Input: [1,2,3]
Output: [2,4]
Explanation: numeral 123 denotes the input array.

Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: input array represents a number 4321.

Ideas to answer:
two cases discussed, the last element of the array is less than 9, add it directly to the output
otherwise, is divided into two cases, one case each element is an array of 9, the array capacity is needed, otherwise nondilatent; whether or not expansion, beginning from the last plus one, plus 1 if the element 10, the position is set to 0, a value plus a front element (the binary equivalent).

After the question sense:
The method is started, the array into numerical value, then add 1 to an array, once the results of a long array, will overflow error. It is also the correct method.

java version of personal answer (only with function):

class Solution {
    public int[] plusOne(int[] digits) {
        //末尾数小于8,直接加1
        if(digits[digits.length-1]<=8){
            digits[digits.length-1]+=1;
            return digits;
        }
        
        //如果每个数都为9,才扩容,否则不扩容
        int count=0;
        //判断是否都为9
        for(int i=0;i<digits.length;i++){
        	if(digits[i]==9){
        		count++;
        	}
        }
        //如果都是9,进行扩容,否则不扩容
        if(count==digits.length){
            int arr[]=new int[digits.length+1];
            for(int i=0;i<digits.length;i++){
            	arr[i+1]=digits[i];
            }
            arr[arr.length-1]+=1;
            for(int i=arr.length-1;i>=0;i--){
                if(arr[i]==10){
                	arr[i]=0;
                	arr[i-1]+=1;
                }
            }
            return arr;
        }else{
            digits[digits.length-1]+=1;
            for(int i=digits.length-1;i>=0;i--){
                if(digits[i]==10){
                    digits[i]=0;
                    digits[i-1]+=1;
                }
            }
        }
        return digits;
    }
}

The answer may have a personal shortcomings, if you have a better idea, welcome the comments area advise, facilitate the exchange of learning together.

Partner may feel nice little upper right corner a praise or attention yo!

Guess you like

Origin blog.csdn.net/fallwind_of_july/article/details/93373430