ShanXiangJC
12/13/2017 - 2:00 PM

[415. Add Strings] #Leetcode #Medium #BigInt(String)

[415. Add Strings] #Leetcode #Medium #BigInt(String)

/* Given two non-negative integers num1 and num2 represented as string, 
    return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
*/

class Solution {
  
  public String addStrings(String num1, String num2) {
    
    // corner case
    if(num1 == null || num1.length() == 0)
      return num2;
    
    if(num2 == null || num2.length() == 0)
      return num1;
    
    // use StringBuilder to store the reversed result.
    StringBuilder sb = new StringBuilder();
    int index1 = num1.length()-1;
    int index2 = num2.length()-1;
    int z = 0;
    
    // iterate two String from right to left
    while(index1 >= 0 || index2 >= 0){
      //empty position will be taken as 0
      int x = index1 >= 0 ? num1.charAt(index1) - '0': 0;
      int y = index2 >= 0 ? num2.charAt(index2) - '0': 0;
      sb.append((x + y + z) % 10);
      z = (x + y + z) / 10;
      index1--;
      index2--;
    }
    
    // add an extra digit
    if(z == 1)
      sb.append("1");
    
    // return reversed StringBuilder
    return sb.reverse().toString();
  
  }

}