Plus One

Problem:
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.

Analysis:
There is no need to has a carry boolean variable. If there is carry, go through plus one to next digit.

Solution:

 class Solution {  
   public int[] plusOne(int[] digits) {  
     boolean hasCarry = false;  
     int len = digits.length;  
       for (int i = len - 1; i >= 0; i--) {  
         if (digits[i] < 9) {  
           digits[i]++;  
           return digits;  
         }   
         digits[i] = 0;  
       }    
     int[] res = new int[len + 1];  
     res[0] = 1;  
     return res;  
   }  
 }  

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array