Given two binary string, return their sum (also a binary string)
Posted 蒋闯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Given two binary string, return their sum (also a binary string)相关的知识,希望对你有一定的参考价值。
主要思路:将二进制转化为十进制,然后进行十进制加法,最后再将加法所得的结果转化为二进制
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)的主要内容,如果未能解决你的问题,请参考以下文章
ICPC上海J.Two Binary Strings Problem(bitset&位运算)
LeetCode-Easy刷题(24) Balanced Binary Tree
Find distance between two give node of binary tree
Convert a given Binary Tree to Doubly Linked List
CMake报错:add_subdirectory not given a binary directory but the given source directory
[SimHash] find the percentage of similarity between two given data