欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Add Binary

程序员文章站 2022-06-04 10:59:05
...

public String addBinary(String a, String b) {
int x = Integer.parseInt(a, 2);
int y = Integer.parseInt(b, 2);
return Integer.toBinaryString(x + y);
}

一开始直接用Integer.toBinaryString()和Integer.parseInt(String, int)方法直接写。小例子还好,可是大例子就过不了,只能强行写了= =


public class Solution {
public String addBinary(String a, String b) {
int length = a.length();
if (b.length() > length)
length = b.length();
String aa = "", bb = "";
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length - a.length(); ++i)
aa = aa + "0";
for (int i = 0; i < length - b.length(); ++i)
bb = bb + "0";
aa = aa + a;
bb = bb + b;
char last = '0';
char cha, chb;
int count = 0;
for (int i = length - 1; i > -1; i--){
cha = aa.charAt(i);
chb = bb.charAt(i);
count = Character.forDigit(2,last) + Character.forDigit(2,cha) + Character.forDigit(2,chb);
sb.setCharAt(i, Character.forDigit(2, count % 2));
last = Character.forDigit(2, count / 2);
}
if (last == '0')
return sb.toString();
else
return '1' + sb.toString();
}
}

注意Character.forDigit是转换char的的方法,可是问题是StringBuilder为空的时候是不能用setCharAt方法的。。。唉
然后还有问题是forDigit写反了 有些还不是用forDigit而是用digit方法

public class Solution {
public String addBinary(String a, String b) {
int length = a.length();
if (b.length() > length)
length = b.length();
String aa = "", bb = "";
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; ++i)
sb.append('0');
for (int i = 0; i < length - a.length(); ++i)
aa = aa + "0";
for (int i = 0; i < length - b.length(); ++i)
bb = bb + "0";
aa = aa + a;
bb = bb + b;
System.out.println(aa);
System.out.println(bb);
char last = '0';
char cha, chb;
int count = 0;
for (int i = length - 1; i > -1; i--) {
cha = aa.charAt(i);
chb = bb.charAt(i);
System.out.println(cha + " " + chb);
count = Character.digit(last, 2) + Character.digit(cha, 2)
+ Character.digit(chb, 2);
System.out.println(count);
sb.setCharAt(i, Character.forDigit(count % 2, 2));
last = Character.forDigit(count / 2, 2);
}
if (last == '0')
return sb.toString();
else
return '1' + sb.toString();
}
}

对了Collections.frequency(Collection<T>, T object)方法可以统计某个object出现的次数
上面的代码其实还是出错 "Internal Error" 不知道为什么
下面找了个示例代码 显然要比我写的好很多啊唉。。。

public class Solution {
public String addBinary(String a, String b) {
// Start typing your Java solution below
// DO NOT write main() function
int l1 = a.length(), l2 = b.length();

StringBuilder sb = new StringBuilder();
int carry = 0;

for (int i = 0; i < Math.max(l1, l2); i++) {
int b1 = getBitAt(a, l1-1-i), b2 = getBitAt(b, l2-1-i);
int sum = b1 + b2 + carry;
sb.append(sum%2);
carry = sum/2;
}
if (carry == 1) {
sb.append(1);
}
return sb.reverse().toString();
}

public int getBitAt(String s, int index) {
if (index < 0) {
return 0;
}
if (s.charAt(index) == '0') {
return 0;
}
else {
return 1;
}
}
}

额 我现在想一下 要是开始把Integer改成Long,说不定就能过了测试了汗。。。当然还是不标准啦~