给你两个二进制字符串 a
和 b
,以二进制字符串的形式返回它们的和。
示例 1:
输入:a = "11", b = "1" 输出:"100"
示例 2:
输入:a = "1010", b = "1011" 输出:"10101"
class Solution {public String addBinary(String a, String b) {if(a.length()==0) return b;if(b.length()==0) return a;String s = "";String ca = new StringBuffer(a).reverse().toString();String cb = new StringBuffer(b).reverse().toString();int t=0;int i=0;while (i<ca.length() && i<cb.length()){t += (ca.charAt(i)-'0') + (cb.charAt(i)-'0');s += Integer.toString(t%2);t=t/2;i++;}while (i<ca.length()){t += (ca.charAt(i)-'0');s += Integer.toString(t%2);t=t/2;i++;}while (i<cb.length()){t += (cb.charAt(i)-'0');s += Integer.toString(t%2);t=t/2;i++;}if(t!=0) s+='1';return new StringBuffer(s).reverse().toString();}
}