标签:style blog class code java tar
少数次通过
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 int[] carry=new int[digits.length+1]; 4 int[] results=new int[digits.length+1]; 5 carry[digits.length]=1; 6 int index=digits.length-1; 7 for(int i=index; i>=0; i--){ 8 carry[i]=(int)((digits[i]+carry[i+1])/10); 9 digits[i]=(digits[i]+carry[i+1])%10; 10 } 11 if(carry[0]==0){ 12 return digits; 13 }else if(carry[0]==1){ 14 for(int k=digits.length-1; k>=0; k--){ 15 results[k+1]=digits[k]; 16 } 17 results[0]=1; 18 } 19 return results; 20 } 21 }
别人的solution:
Solution1 :
1 public class Solution { 2 public int[] plusOne(int[] digits) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 boolean isNines = true; 6 for(int i=0;i<digits.length;i++) 7 if(digits[i]!=9){ 8 isNines = false; 9 break; 10 } 11 12 if(isNines){ 13 int[] result = new int[digits.length+1]; 14 result[0] = 1; 15 return result; 16 } 17 18 int[] result = digits; 19 20 int p = result.length-1; 21 int increment=1; 22 23 while(p>=0 && increment>0){ 24 int sum = digits[p]+increment; 25 result[p] = sum%10; 26 increment = sum/10; 27 p--; 28 } 29 return result; 30 } 31 }
Solution 2:
1 public class PlusOne { 2 public int[] plusOne(int[] digits) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int carry = 1; 6 int temp; 7 boolean needMoreDigit = true; 8 for (int i = digits.length - 1; i >= 0; i--) { 9 temp = (digits[i] + carry) % 10; 10 // System.out.println("i "+i+"temp "+temp); 11 carry = (digits[i] + carry) / 10; 12 digits[i] = temp; 13 if (carry == 0) { 14 needMoreDigit = false; 15 break; 16 } 17 } 18 // System.out.println("nn"+needMoreDigit); 19 if (!needMoreDigit) { 20 return digits; 21 } else { 22 int[] newDigits = new int[digits.length + 1]; 23 newDigits[0] = carry; 24 for (int i = 1; i <= digits.length; i++) { 25 newDigits[i] = digits[i - 1]; 26 } 27 return newDigits; 28 } 29 30 } 31 public static void main(String[] args){ 32 PlusOne o = new PlusOne(); 33 int[]digits = {9,8,7,6,5,4,3,2,1,0}; 34 int[] result = o.plusOne(digits); 35 for(int i=0;i<result.length;i++){ 36 System.out.print(" "+result[i]); 37 } 38 } 39 40 }
Leetcode: Plus One,布布扣,bubuko.com
标签:style blog class code java tar
原文地址:http://www.cnblogs.com/EdwardLiu/p/3703630.html