Given a non-negative number rePResented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
據說這道題在google的面試中出現頻率很高呀。雖然不知道為什么。~
這道題還是很好思考的。
比較麻煩的是如果到最開頭還是需要繼續進位的話就要新建一個長度是原來array長度+1的數組然后將第一個數設為1,后面和原array的一樣。
至于為啥就不說了。應該很好理解的。~
另外記得要寫break,不用進位后計算也就停止了。
代碼如下:
public class Solution { public int[] plusOne(int[] digits) { int length=digits.length; for(int i=length-1;i>=0;i--){ if(digits[i]==9){ digits[i]=0; }else{ digits[i]=digits[i]+1; break; } if(i==0&&digits[i]==0){ int[] temp=new int[digits.length+1]; temp[0]=1; for(int j=1;j<digits.length+1;j++){ temp[j]=digits[j-1]; } digits=temp; } } return digits; }}新聞熱點
疑難解答