Title Description
Given a nonnegative integer represented by a nonempty array of integers, add one to the number. The highest number is placed at the top of the array, and each element of the array only stores one number. You can assume that except for the integer 0, this integer does not start with zero. Example 1: Input: [1,2,3] Output: [1,2,4] Explanation: the input array represents the number 123. Example 2: Input: [4,3,2,1] Output: [4,3,2,2] Explanation: the input array represents the number 4321.
Topic idea: just divide it into good categories
Title Code:
package leetcode.easy.week01; public class problem66 { public int[] plusOne(int[] digits) { //Start with 0 if(digits[0]==0){ digits[0]=1; return digits; } //It doesn't start with 0 and the last digit is not 9. if(digits[digits.length-1]!=9){ digits[digits.length-1]=digits[digits.length-1]+1; return digits; } //Everyone is 9 for(int b=0;b<digits.length;b++){ if(digits[b] !=9){ break; } if(b==digits.length-1){ //That's to say, every bit is 9. int[] result=new int[digits.length+1]; for(int c=0;c<result.length;c++){ if(c==0){ result[c]=1; }else{ result[c]=0; } } return result; } } //It doesn't start with 0, the last bit is 9, but not everyone else is 9, that is, the returned array length is the same. if(digits[digits.length-1]==9){ for(int a=digits.length-1;a>-1;a--){ if(digits[a]!=9){ digits[a]=digits[a]+1; break; }else{ digits[a]=0; } } } return digits; } public static void main(String[] args) { problem66 pro=new problem66(); int[] ints = pro.plusOne(new int[]{8,9,9,9}); } }