Simple Java Solution


  • 0
    public String addStrings(String num1, String num2) {
    	if(num1==null || num2==null) return "";
    	if(num1.length()<num2.length()) {
    		int diff = num2.length()-num1.length();
    		for(int i=0;i<diff;i++) {
    			num1 = "0"+num1;
    		}
    	} else {
    		int diff = num1.length()-num2.length();
    		for(int i=0;i<diff;i++) {
    			num2 = "0"+num2;
    		}
    	}
    	char[] chars1 = num1.toCharArray();
    	char[] chars2 = num2.toCharArray();
    	StringBuilder res = new StringBuilder();
    	int carry = 0;
    	for(int i=chars1.length-1;i>=0;i--) {
    		int digit1 = chars1[i]-'0';
    		int digit2 = chars2[i]-'0';
    		int nextDigit = (digit1+digit2+carry)%10;
    		carry = (digit1+digit2+carry)/10;
    		res = res.insert(0, nextDigit);
    	}
    	if(carry>0)
    		res = res.insert(0, carry);
    	return res.toString();
    }
    

Log in to reply
 

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