Super Clean JAVA Code


  • 0
    A
    public String addStrings(String num1, String num2) {
    	int i = num1.length() - 1;
    	int j = num2.length() - 1;
    	int carry = 0;
    	StringBuilder sb = new StringBuilder();
    	while (i >= 0 || j >= 0 || carry > 0) {
    		int a = (i >= 0) ? num1.charAt(i--) - '0' : 0;
    		int b = (j >= 0) ? num2.charAt(j--) - '0' : 0;
    		int r = (a + b + carry) % 10;
    		carry = (a + b + carry) / 10;
    		sb.insert(0, String.valueOf((char) (r + '0')));
    	}
    	return sb.toString();
    }

Log in to reply
 

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