Given a non-negative number represented as an array of digits, plus one to the number.
The digits is stored such, the most significant digit was at the head of the list.
Subscribe to see which companies asked this question
The main idea is to use an int array to simulate the calculation of the decimal number plus 1, where the need to pay attention is the overflow situation.
1 Public classSolution {2 Public int[] PlusOne (int[] digits) {3 intLen =digits.length;4digits[len-1]++;5 BooleanFlag =false;//whether overflow6 for(inti=len-1; i>=0;i--){7 if(Digits[i] >= 10) {8 if(I! = 0){9digits[i-1]++;Ten}Else{ OneFlag =true; A } -Digits[i]-= 10; - } the } - if(Flag = =true){ - int[] res =New int[Len+1]; -Res[0] = 1; + for(inti = 0;i<len;i++){ -RES[I+1] =Digits[i]; + } A returnRes; at}Else{ - returndigits; - } - - } -}
Solutions Plus One Java