Thursday, January 1, 2015

Plus One (LeetCode Array)

Question: 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.

Idea: From the end of the input array, keep adding 1 until the carry becomes zero. There is a special case that if all the digits are 9, e.g. 999999. The carry will still be 1 after adding the most significant digit. Then we need to initial another array with the first digit as 1 and all the rest digits as 0.

Time: O(n) Space: O(n) (worst case when all digits are 9, we need a new array to store the result)

Code:
 public class Solution {  
   public int[] plusOne(int[] digits) {  
     for(int i=digits.length-1;i>=0;i--)  
     {  
       digits[i]=digits[i]+1;  
       if(digits[i]>=10)  
         digits[i]-=10;  
       else  
         return digits;  
     }  
     int[] result=new int[digits.length+1];  
     result[0]=1;  
     return result;  
   }  
 }  

No comments:

Post a Comment