Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
[解题思路]
将a,b转成10进制相加得到结果再转成二进制,可以过small,跑large时溢出
"10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101", "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011" | "11101000101011001000011011000001100011110011010010011000000000" | "110111101100010011000101110110100000011101000101011001000011011000001100011110011010010011000000000" |
1 public class Solution { 2 public String addBinary(String a, String b) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 if(a == null || a.equals("")){ 6 return b; 7 } 8 if(b == null || b.equals("")){ 9 return a; 10 } 11 12 long a1 = 0; 13 for(int i = 0; i < a.length(); i++){ 14 a1 = a1 * 2 + (a.charAt(i) - '0'); 15 } 16 long b2 = 0; 17 for(int i = 0; i < b.length(); i++){ 18 b2 = b2 * 2 + (b.charAt(i) - '0'); 19 } 20 21 long sum = a1 + b2; 22 if(sum == 0){ 23 return "0"; 24 } 25 ArrayList<Long> binarySum = new ArrayList<Long>(); 26 while(sum > 0){ 27 binarySum.add(sum % 2); 28 sum = sum / 2; 29 } 30 StringBuilder sb = new StringBuilder(); 31 for(int i = binarySum.size() - 1; i >= 0; i-- ){ 32 sb.append(binarySum.get(i)); 33 } 34 return sb.toString(); 35 } 36 }
字符串操作
1. StringBuilder.reverse()
2. 最后一位的进位需要加上
1 public class Solution { 2 public String addBinary(String a, String b) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 if(a == null || a.equals("")){ 6 return b; 7 } 8 if(b == null || b.equals("")){ 9 return a; 10 } 11 StringBuilder a1 = new StringBuilder(a); 12 a1.reverse(); 13 StringBuilder b1 = new StringBuilder(b); 14 b1.reverse(); 15 StringBuilder result = new StringBuilder(); 16 int len = Math.max(a.length(), b.length()); 17 int carry = 0; 18 for(int i = 0; i < len; i++){ 19 int t1 = (i >= a.length() ? 0 : (a1.charAt(i) - '0')); 20 int t2 = (i >= b.length() ? 0 : (b1.charAt(i) - '0')); 21 int t3 = t1 + t2 + carry; 22 carry = t3 / 2; 23 t3 = t3 % 2; 24 result.append(t3); 25 } 26 if(carry != 0) 27 result.append(carry); 28 result.reverse(); 29 return result.toString(); 30 } 31 }