Given two binary string, return their sum (also a binary string)

时间:2022-01-16 17:34:20

主要思路:将二进制转化为十进制,然后进行十进制加法,最后再将加法所得的结果转化为二进制

public class BinarySum2 {

public static void main(String[] args) {
  String a = "111";
  String b = "101";
  int sumInt = toInt(a) + toInt(b);
  StringBuffer sb = toBinary(sumInt);
  for(int i = sb.length()-1; i >= 0; --i){
  System.out.print(sb.charAt(i));
  }
}
public static int toInt(String a) {
  int sum = 0;
  for(int i = 0; i < a.length(); ++i){
  int d = Integer.parseInt(a.substring(i,i+1));
  sum += d*(Math.pow(2, a.length()-i-1));
  }
  return sum;
}
public static StringBuffer toBinary(int sumInt) {
  StringBuffer sb = new StringBuffer();
  while(sumInt / 2 != 0){
  int remain = sumInt % 2;
  sb.append(remain);
  sumInt = sumInt/2;
  }
  sb.append(1);
  return sb;
  }
}