public class Solution67 {
public static String addBinary(String a, String b) {
int aLength = a.length();
int bLength = b.length();
StringBuilder sb = new StringBuilder();
int carry = 0;
while(Math.max(aLength, bLength) > 0) {
int aNum = aLength > 0 ? (a.charAt(aLength---1) - '0') : 0;
int bNum = bLength > 0 ? (b.charAt(bLength---1) - '0') : 0;
int cNum = aNum + bNum + carry;
sb.append(cNum%2);
carry = cNum / 2;
}
return (carry == 1)?sb.append(1).reverse().toString():sb.reverse().toString(); }
public static void main(String[] args)
{
String a="100";
String b="1";
System.out.println(addBinary(a,b));
}
}
Add Binary 测试版
最新推荐文章于 2024-10-16 10:13:45 发布