My code:
public class Solution {
public String addBinary(String a, String b) {
if (a == null || a.length() == 0 || b == null || b.length() == 0)
return null;
int len = Math.max(a.length(), b.length()) + 1;
String aReverse = "";
for (int i = a.length() - 1; i >= 0; i--)
aReverse += a.charAt(i);
String bReverse = "";
for (int i = b.length() - 1; i >= 0; i--)
bReverse += b.charAt(i);
byte[] carry = new byte[len];
for (int i = 0; i < len - 1; i++) {
if (i >= Math.min(aReverse.length(), bReverse.length())) {
if (aReverse.length() >= bReverse.length()) {
byte sum = (byte) (aReverse.charAt(i) - 0x30 + carry[i]);
carry[i + 1] = (byte) (sum >> 0x01);
carry[i] = (byte) (sum & 0x01);
}
else {
byte sum = (byte) (bReverse.charAt(i) - 0x30 + carry[i]);
carry[i + 1] = (byte) (sum >> 0x01);
carry[i] = (byte) (sum & 0x01);
}
}
else {
byte sum = (byte) (aReverse.charAt(i) - 0x30 + bReverse.charAt(i) - 0x30 + carry[i]);
carry[i + 1] = (byte) (sum >> 0x01);
carry[i] = (byte) (sum & 0x01);
}
}
int resultLen = 0;
if (carry[len - 1] == 0)
resultLen = len - 1;
else
resultLen = len;
String resultStr = "";
for (int i = 0 ; i < resultLen; i++)
resultStr += (char) (carry[resultLen - i - 1] + 0x30);
for (int i = 0; i < resultStr.length(); i++) {
if (resultStr.charAt(0) == '0') {
if (i != resultLen - 1)
resultStr = resultStr.substring(1, resultStr.length());
}
else
break;
}
return resultStr;
}
public static void main(String[] args) {
Solution test = new Solution();
System.out.println(test.addBinary("011", "1"));
}
}
My test result:
这次作业不难,但是有些细节要注意下。
首先是,Java 比特级操作。
无论是移位操作,还是加减操作,最后都会转换为int类型,进行处理,所以返回值都是int,如果需要进行比特操作,还需要对结果强制转换下。
还有个地方就是,需要考虑哪个加数更长些,然后对这个情况进行处理,防止溢出。
差不多就这样了。
下面粘贴一个Java 位操作的的博客。
http://dogstar.iteye.com/blog/227625
**
总结:Java 位操作,返回仍是 int, 需要再次进行强制转换为byte。
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public String addBinary(String a, String b) {
if (a == null || a.length() == 0)
return b;
else if (b == null || b.length() == 0)
return a;
/** reverse string for plus */
StringBuilder p1 = new StringBuilder(a);
p1 = p1.reverse();
StringBuilder p2 = new StringBuilder(b);
p2 = p2.reverse();
int carry = 0;
StringBuilder ret = new StringBuilder();
int i = 0;
int j = 0;
while (i < p1.length() || j < p2.length()) {
if (i >= p1.length()) {
int sum = p2.charAt(j) - 48 + carry;
carry = sum / 2;
ret.append(sum % 2);
j++;
}
else if (j >= p2.length()) {
int sum = p1.charAt(i) - 48 + carry;
carry = sum / 2;
ret.append(sum % 2);
i++;
}
else {
int sum = p1.charAt(i) - 48 + p2.charAt(i) - 48 + carry;
carry = sum / 2;
ret.append(sum % 2);
i++;
j++;
}
}
if (carry != 0)
ret.append(carry);
return ret.reverse().toString();
}
}
感觉这次的代码简单理解好多。
和刚刚那道题目,
- Add Two Numbers
http://www.jianshu.com/p/37d4945d5e61
很像。
也是反转下。然后加起来。结果再反转回去。
注意, '0' 的十进制值是 48, OX30
Anyway, Good luck, Richardo!