Java solution using stack


  • 0
    R

    public class Solution {
    public String addStrings(String num1, String num2) {
    if(num1 == "" && num2 == "") {
    return null;
    }
    if(num1 == null) {
    return num2;
    }
    if(num2 == null) {
    return num1;
    }
    int carry = 0;
    String ret_str = "";
    int max_len = Math.max(num1.length(), num2.length());
    int min_len = Math.min(num1.length(), num2.length());
    int j = min_len-1;
    int num1_int = 0;
    int num2_int = 0;
    Stack stk = new Stack();

        for(int i = max_len-1 ; i >= 0; i--) {
            
            num1_int = 0;
            num2_int = 0;
            
            if(num1.length() == num2.length()) {
               num1_int = num1.charAt(i) - 48;
               num2_int = num2.charAt(i) - 48;
            } else {
              if(num1.length() == min_len && j >= 0) {
              num1_int = num1.charAt(j) - 48;
              j--;
              } else if(num1.length() != min_len) {
                  num1_int = num1.charAt(i) - 48;
              }
              
              if(num2.length() == min_len && j >= 0) {
              num2_int = num2.charAt(j) - 48;
              j--;
              } else if(num2.length() != min_len){
                   num2_int = num2.charAt(i) - 48;
              }
            }
    
            
            int num = num1_int + num2_int + carry;
            carry = num/10;
            num = num % 10;
    
            stk.push(num);
            
            if(i == 0 && carry != 0) {
                stk.push(carry);
            }
        }
        
        int temp = stk.size();
        for(int k = 0; k < temp; k++) {
            ret_str = ret_str + String.valueOf(stk.pop());
        }
         return ret_str;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.