2个回答

``````import java.math.*;

/**
* BitInteger
*/
public class BitInteger {

public static void main(String[] args) {
String bitStr1 = "0101000";
String bitStr2 = "1010110";
BigInteger a = new BigInteger(bitStr1, 2);
BigInteger b = new BigInteger(bitStr2, 2);

System.out.println("a+b as :" + a.toString() + "+" + b.toString() + "=" + a.add(b).toString());
System.out.println("a+b as :" + a.toString(2) + "+" + b.toString(2) + "=" + a.add(b).toString(2));
}
}
``````

``````a+b as :40+86=126
a+b as :101000+1010110=1111110
``````

``````public static void main(String[] args) {
}
public static String add(String a,String b){
if (null ==a || null ==b) {
return "null";
}
if (a.length() > 100 || b.length() > 100) {
return "data too long";
}
StringBuilder sb=new StringBuilder();
int x=0;
int y=0;
int pre=0;
int sum=0;
while(a.length()!=b.length()){
if(a.length()>b.length()){
b="0"+b;
}else{
a="0"+a;
}
}
for(int i=a.length()-1;i>=0;i--){
x=a.charAt(i)-'0';
y=b.charAt(i)-'0';
sum=x+y+pre;
if(sum>=2){
pre=1;
sb.append(sum-2);
}else{
pre=0;
sb.append(sum);
}
}
if(pre==1){
sb.append("1");
}
return sb.reverse().toString();
}
``````