2015年9月25日星期五

Leetcode 66 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.
Solution 1: simple math O(n) solution
 public class Solution {  
   public int[] plusOne(int[] digits) {  
     int carry=1;  
     int n=digits.length;  
     for (int i=n-1; i>=0; i--) {  
       int temp=digits[i];  
       digits[i]=(temp+carry)%10;  
       carry=(temp+carry)/10;  
     }  
     if (carry==0) return digits;  
     int[] res=new int[n+1];  
     res[0]=1;  
     return res;  
   }  
 }  

没有评论:

发表评论