java 20ms solution by charArray instead of stringbuffer


  • 0
    C
    public String addStrings(String num1, String num2) {
    	char[] charArrNum1 = num1.toCharArray();
    	char[] charArrNum2 = num2.toCharArray();
    	char[] result = new char[charArrNum1.length > charArrNum2.length? charArrNum1.length + 1 : charArrNum2.length + 1];
    	
    	int carry = 0, index = result.length-1;
    	for(int end1 = charArrNum1.length-1, end2 = charArrNum2.length-1; end1 >= 0 || end2 >=0; end1--, end2--){
    		int n1 = end1 >= 0? charArrNum1[end1] - '0' : 0;
    		int n2 = end2 >= 0? charArrNum2[end2] - '0' : 0;
    		int tempRes = n1 + n2 + carry;
    		result[index--] = (char) ('0' + (tempRes % 10));
    		carry = tempRes / 10;
    	}
    	result[index] = (char) ('0' + carry);
        return carry==0? new String(result, 1, result.length-1) : new String(result, 0, result.length);
    }

Log in to reply
 

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