Add Binary:Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
题意:本题意思很明了,给定2个String,分别存储了用二进制表示的数,实现二进制的加法。
思路:从右向左逐位相加,注意进位即可。
代码:
public String addBinary(String a, String b) { int flag = 0; int aIndex = a.length() - 1; int bIndex = b.length() - 1; String c=""; while(aIndex>=0&&bIndex>=0){ int num = a.charAt(aIndex) - '0' + (b.charAt(bIndex) - '0') + flag; flag = num/2; num %= 2; c = String.valueOf((char)(num+'0'))+ c; aIndex --; bIndex --; } while(aIndex >= 0){ int num = a.charAt(aIndex) - '0' + flag; flag = num /2; num %= 2; c =String.valueOf((char)(num+'0')) + c; aIndex--; } while(bIndex >= 0){ int num = b.charAt(bIndex) - '0' + flag; flag = num /2; num %= 2; c =String.valueOf((char)(num+'0')) + c; bIndex--; } if(flag>0){ c = String.valueOf(flag) + c; } return c; }