码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-02-22 11:35:49      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:十进制   ringbuf   class   integer   加法   length   rem   ++   char   

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

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;
  }
}

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

标签:十进制   ringbuf   class   integer   加法   length   rem   ++   char   

原文地址:http://www.cnblogs.com/huaiyinxiaojiang/p/6427925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!