leetcode--二進位制求和(AddBinary)--java
阿新 • • 發佈:2019-01-26
package leetcode;
/* Given two binary strings, return their sum (also a binary string).
* For example,
* a = "11"
* b = "1"
* Return "100".
*/
import java.lang.Math;
public class AddBinary {
public String addBinary(String a, String b) {
if (a == null || a.length() == 0) //如果a為空,則返回b;反之則返回a
return b;
if (b == null || b.length() == 0)
return a;
int i = a.length() - 1; //獲取a,b的長
int j = b.length() - 1;
int carry = 0; //進位標誌,初始化為0
StringBuilder res = new StringBuilder();
while (i >= 0 && j >= 0) { // a,b都不為空時,從後往前遍歷,從低位開始相加
int digit = (int) (a.charAt(i) - '0' + b.charAt (j) - '0') + carry;
carry = digit / 2; //儲存下一個carry位:逢2進位
digit %= 2; //取餘,儲存當前位(進位後)的值
res.insert(0, digit); //插入到res中
i--;
j--;
}
//a更長時,處理a餘下的數位
while (i >= 0) {
int digit = (int) (a.charAt(i) - '0') + carry;
carry = digit / 2;
digit %= 2;
res.insert(0, digit) ;
i--;
}
//b更長時,處理b餘下的數位
while (j >= 0) {
int digit = (int) (b.charAt(j) - '0') + carry;
carry = digit / 2;
digit %= 2;
res.insert(0, digit);
j--;
}
//加完之後,第一位也需進位
if (carry > 0) {
res.insert(0, carry);
}
return res.toString();
}
}