1. 程式人生 > >leetcode 415. Add Strings

leetcode 415. Add Strings

/**
 * 415. Add Strings
 * @param num1
 * @param num2
 * @return
 * 2017年3月16日下午9:22:21
 */
public String addString(String num1, String num2) {
	int idx1 = num1.length()-1;
	int idx2 = num2.length()-1;
	StringBuilder sbdr = new StringBuilder();
	int carry = 0, remainder = 0, sum = 0;
	for (; idx1>=0 && idx2>=0; idx1--, idx2--) {
		sum = num1.charAt(idx1) + num2.charAt(idx2) - 2*'0' + carry;
		carry = sum / 10;
		remainder = sum % 10;
		sbdr.append(remainder);
	}
	
	if (idx1>=0) {
		for (; idx1>=0; idx1--) {
			sum = num1.charAt(idx1)- '0' + carry;
			carry = sum / 10;
			remainder = sum % 10;
			sbdr.append(remainder);
		}
	}
	else {
		for (; idx2>=0; idx2--) {
			sum = num2.charAt(idx2)- '0' + carry;
			carry = sum / 10;
			remainder = sum % 10;
			sbdr.append(remainder);
		}
	}
	if (carry!=0)
		return sbdr.append(carry).reverse().toString();
	return sbdr.reverse().toString();
}