leetcode--Plus One

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.

public class Solution {
    /**very fundamental problem.<br>
     * @author Averill Zheng
     * @version 2014-06-05
     * @since JDK 1.7
     */ 
    public int[] plusOne(int[] digits) {
       int length = digits.length;
       int[] result = null;
       if(length > 0){
    	   int[] temp = new int[length + 1];
    	   int carry = 1;
    	   for(int i = length - 1; i > -1; --i){
    		   int sum = digits[i] + carry;
    		   carry = sum / 10;
    		   temp[i + 1] = sum % 10;
    	   }
    	   if(carry != 0)
    		   temp[0] = 1;
    	   if(temp[0] != 0)
    		   result = temp;
    	   else{
    		   result = new int[length];
    		   for(int i = 1; i < length + 1; ++i)
    			   result[i - 1] = temp[i];
    	   }   
       }
       return result;    
    }
}

  

posted @ 2014-06-07 02:27  Averill Zheng  阅读(207)  评论(0编辑  收藏  举报