1. 程式人生 > >leetcode解題之67 # Add Binary Java版

leetcode解題之67 # Add Binary Java版

67. Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

二進位制加法,用0補齊最短字串左側,至兩字串等長,如 a = "1111", b = "1",其基本實現就是實現 a = "1111",b = "0001",這樣相加,只是程式碼更簡潔。
public String addBinary(String a, String b) {
		int lengthA = a.length();
		int lengthB = b.length();
		// carry 為初始進位制位數
		int val, tempA, tempB, carry = 0;
		StringBuffer sb = new StringBuffer();
		int maxLength = lengthA >= lengthB ? lengthA : lengthB;
		for (int i = 0; i < maxLength; i++) {
			// 從右邊開始逐位取出字串 a、b 的字元值 tempA 和 tempB,如果長度不足,則用0替代
			tempA = lengthA > i ? a.charAt(lengthA - i - 1) - '0' : 0;
			tempB = lengthB > i ? b.charAt(lengthB - i - 1) - '0' : 0;
			val = tempA + tempB + carry;
			carry = val / 2;
			val = val % 2;
			sb.append(val + "");
		}
		// 如果最高位有進位,則最高位還要加一位 1
		if (carry == 1)
			sb.append(carry);
		// 翻轉結果
		return sb.reverse().toString();
	}