package com.fishercoder.solutions;

/**
 * 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.
 */
public class _66 {

  public static class Solution1 {
    public int[] plusOne(int[] digits) {
      boolean carry = false;
      int len = digits.length;
      int[] temp = digits;
      //process the last digit at first, to get carry value
      if (digits[len - 1] + 1 == 10) {
        carry = true;
        temp[len - 1] = 0;
      } else {
        temp[len - 1] += 1;
        return temp;
      }

      //start from the second last element
      for (int i = len - 2; i >= 0; i--) {
        if (carry && temp[i] + 1 == 10) {
          temp[i] = 0;
          carry = true;
        } else if (carry) {
          temp[i] += 1;
          carry = false;
        }
      }
      if (carry && temp[0] == 0) {
        int[] res = new int[len + 1];
        res[0] = 1;
        //all the rest of the numbers should all be zeroes, so we don't need to copy from the original array
        return res;
      }
      return temp;
    }
  }
}

@@ -337,35 +337,8 @@
 %7B%0A  
-    boolean carry = false;%0A
     
@@ -366,24 +366,26 @@
 ngth;%0A      
+  
 int%5B%5D temp =
@@ -403,165 +403,101 @@
     
-//process the last digit at first, to get carry value%0A      if (digits%5Blen - 1%5D + 1 == 10) %7B%0A        carry = true;%0A        temp%5Blen -
+  %0A        for (int i = len - 1; i %3E= 0; i--) %7B%0A            if (temp%5Bi%5D +
  1
-%5D
  =
- 0;%0A      %7D else %7B%0A
+= 10) %7B%0A        
     
@@ -509,21 +509,14 @@
 emp%5B
-len - 1
+i
 %5D 
-+
 = 
-1
+0
 ;%0A  
@@ -525,319 +525,116 @@
     
-return temp;%0A      %7D%0A%0A      //start from the second last element%0A      for (int i = len - 2; i %3E= 0; i--) %7B%0A        if (carry && temp%5Bi%5D + 1 == 10) %7B%0A          temp%5Bi%5D = 0;%0A          carry = true;%0A        %7D else if (carry) %7B%0A          temp%5Bi%5D += 1;%0A          carry = false;%0A        %7D%0A      %7D%0A      if (carry && 
+    %7D else %7B%0A                temp%5Bi%5D += 1;%0A                return temp;%0A            %7D%0A        %7D%0A        if (
 temp
@@ -641,24 +641,28 @@
 %5B0%5D == 0) %7B%0A
+    
         int%5B
@@ -695,16 +695,20 @@
         
+    
 res%5B0%5D =
@@ -710,24 +710,16 @@
 %5B0%5D = 1;
-%0A       
  //all t
@@ -816,24 +816,28 @@
 ray%0A        
+   
+ 
 return res;%0A
@@ -842,24 +842,39 @@
 ;%0A      
-%7D%0A
+  %7D else %7B%0A   
       
+   
 return t
@@ -874,24 +874,34 @@
 eturn temp;%0A
+        %7D%0A
     %7D%0A  %7D%0A%7D%0A

Update _66.java (#37)