Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题解:简单的二进制加法模拟。a,b的最后以为对齐开始进行加法,用carries保存进位,如果加完后最高位还有进位,那么要在结果的最前面加一个1。
代码如下:
1 public class Solution { 2 public String addBinary(String a, String b) { 3 if(a == null || a.length() == 0) 4 return b; 5 if(b == null || b.length() == 0) 6 return a; 7 8 String s = new String(); 9 int carries = 0; 10 int a_kepeler = a.length()-1; 11 int b_kepeler = b.length()-1; 12 13 while(a_kepeler >= 0 && b_kepeler >= 0){ 14 int sum = carries + a.charAt(a_kepeler) - '0' + b.charAt(b_kepeler) - '0'; 15 carries = sum / 2; 16 sum = sum % 2; 17 s = String.valueOf(sum) + s; 18 a_kepeler--; 19 b_kepeler--; 20 } 21 22 while(a_kepeler >= 0){ 23 int sum = carries + a.charAt(a_kepeler) - '0'; 24 carries = sum / 2; 25 sum = sum % 2; 26 s = String.valueOf(sum) + s; 27 a_kepeler--; 28 } 29 30 while(b_kepeler >= 0){ 31 int sum = carries + b.charAt(b_kepeler) - '0'; 32 carries = sum / 2; 33 sum = sum % 2; 34 s = String.valueOf(sum) + s; 35 b_kepeler--; 36 } 37 38 if(carries > 0) 39 s = "1" + s; 40 41 return s; 42 } 43 }
上述代码还可以优化,就是如果a的长度小于b,就把a,b交换,使得a总是较长的那个,那么就可以省略第30~36行的while循环了。