LeetCode # Array # Easy # 66. Plus One

topic:

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Idea: The main thing is to think clearly about the handling of cases where one digit = 9 or all = 9.

1  class Solution {
 2      public  int [] plusOne( int [] digits) {
 3          int size = digits.length;  
 4          int sum = 0 ;  
 5          for ( int i = size - 1; i >= 0; i-- ) { //Start from the one digit
              sum = digits[i] + 1 ; 7 if  
 ( sum == 10 ) { //If the current number=9, then sum=10, it should be carried by 1, so the current value is set to 0. Previous digit +
 1. 8                  digits[i] = 0; continue ;
 9             }  
 10 else { //Otherwise, jump out of loop
 11                                            digits[i] = sum; break ;
 12              }  
 13          }  
 14          if (sum == 10 ){ //If the highest digit=9, then sum=10. At this point, an array should be built, one digit larger than digital, and then Copy digital to this array.
15              int [] result = new  int [size + 1 ];  
 16              for ( int j = 0; j < size; j++ )  
 17                  result[j + 1] = digits[j];  
 18              result[0] = 1 ;  
 19              return result;  
 20          }  
 21          else   
22              return digits;
23     }
24 }

Reference: https://blog.csdn.net/sunshine0_0/article/details/54917835

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325228467&siteId=291194637