leetcode解題之67 # Add Binary Java版
阿新 • • 發佈:2018-12-24
67. Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
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(); }