Question:
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.
Analysis:
A non-negative number is represented by an array, and then the number is added one.
This topic mainly needs to consider special cases: the numbers are all 9; some of the numbers are 9; the general situation. So take all the circumstances into account and OK.
Answer:
Public classSolution { Public int[] PlusOne (int[] digits) { if(Digits = =NULL) return NULL; if(digits[digits.length-1]! = 9) {Digits[digits.length-1] + +; returndigits; } BooleanFlag =true; for(inti=0; i<digits.length; i++) { if(Digits[i]! = 9) {flag=false; Break; } } if(Flag = =true) {//9 of all digits int[] res =New int[Digits.length + 1]; res[0] = 1; returnRes; } Else{//the last one is 9 for(intI=digits.length-1; i>=0; i--) { if(Digits[i] = = 9) Digits[i]= 0; Else{Digits[i]++; returndigits; } } } returndigits; } }
Leetcode--Plus One