Plus One leetcode java


題目

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.

 

題解

這道題就是實現題。

先對原數組進行處理。從數組最后一位開始往前檢查,如果當前數字是<9的,說明你加1無需進位,從循環跳出即可,如果當前數字等於9,說明加1涉及進位,且加1后當前數字應記為0,繼續循環處理。

當對原數組處理完后,還需要判斷當前第0位是不是已經變為0了,如果已經變為0了說明是類似99+1這種,需要進位。其他則不需要。

一般對數字進行操作的題都要考慮邊界,尤其是溢出問題。

 

代碼如下:

 1  public  int[] plusOne( int[] digits) {
 2              int length;
 3             length = digits.length;
 4              for( int i = length-1; i>=0; i--){
 5                  if(digits[i]<9){
 6                     digits[i]++;
 7                      break;
 8                 } else{
 9                     digits[i]=0;
10                 }
11             }
12             
13              int[] newdigits;
14              if(digits[0]==0){
15                 newdigits =  new  int[digits.length+1];
16                 newdigits[0]=1;
17                  for( int i=1;i<newdigits.length;i++){
18                     newdigits[i]=digits[i-1];
19                 }
20             } else{
21                 newdigits =  new  int[digits.length];
22                  for( int i=0;i<digits.length;i++){
23                     newdigits[i]=digits[i];
24                 }
25             }
26               return newdigits;
27         }

 另外一種考慮溢出的解法如下:

 

 1        public  int[] plusOne( int[] digits) {
 2              for( int i=digits.length-1;i>=0;i--){
 3                 digits[i] =1+digits[i];
 4                 
 5                  if(digits[i]==10)
 6                     digits[i]=0;
 7                  else
 8                      return digits;
 9             }
10 
11              // don't forget over flow case
12               int[] newdigit =  new  int[digits.length+1];
13             newdigit[0]=1;
14              for( int i=1;i<newdigit.length;i++){
15                 newdigit[i] = digits[i-1];
16             }
17              return newdigit;
18         }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM