Readable java solution


  • 0
    V
    public class Solution {
        public String addStrings(String num1, String num2) {
            if(num1.length() == 0){
                return num2;
            }
            if(num2.length() == 0){
                return num1;
            }
            int d = 0 ;
            if(num1.length() == num2.length()){
                d = 0 ;
                return add(num1 , num2 , d);
            }
            if(num1.length() > num2.length()){
                d = num1.length() - num2.length();
                return add(num1 , num2 , d);
            } else {
                d = num2.length() - num1.length();
                return add(num2 , num1 , d);
            }
        }
        
        public static String add(String num1 , String num2 , int d){
            StringBuffer a = new StringBuffer(num1);
            StringBuffer b = new StringBuffer(num2);
            a.reverse();
            b.reverse();
            if(d != 0){
                for(int i = 1 ; i <= d ; i ++){
                    b.append("0");
                }
            }
            int carry = 0;
            StringBuffer result = new StringBuffer();
            for(int i = 0 ; i < a.length() ; i ++){
                int sum = Integer.parseInt(""+a.charAt(i)) + Integer.parseInt("" + b.charAt(i)) + carry;
                carry = sum / 10 ;
                result.append(sum % 10);
            }
    
            if(carry == 0){
                return result.reverse().toString();
            } else {
                result.append(carry);
                return result.reverse().toString();
            }
    }
    }
    

Log in to reply
 

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