Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
每次相加的时候每位会出现0,1 ,2 ,3的情况,其对应的二进制是0,1,0,1.所以采用%2的形式。
进位为0或者1,满2有进位,其余为0。所以采用/2.
对字符串的处理,因为是java会比较简单,强语言类型可以强制转换。显示的强制转换只是方便阅读代码,
所以最好不要依赖jdk实现数据类型的转换。
class Solution { public String addBinary(String a, String b) { int sum = 0;//结果 String res = "" ;//字符串结果 int carries = 0;//进位 int al = a.length()-1; int bl = b.length()-1; //判断长度 if(a.length() > b.length()){ while(bl >= 0){ sum = (int)(a.charAt(al) - '0') + (int)(b.charAt(bl) - '0') + carries; res = String.valueOf(sum%2) + res; carries = sum/2; al--; bl--; } while(al >= 0){ sum = (int)(a.charAt(al)-'0') + carries; res = String.valueOf(sum%2) + res; carries = sum/2; al--; } if(carries == 1){ res = "1" + res; } //System.out.println("a>b的字符串:"+res); return res; }else{ while(al >= 0){ sum = (int)(a.charAt(al)-'0') + (int)(b.charAt(bl) - '0') + carries; res = String.valueOf(sum%2) + res; carries = sum/2; al--; bl--; } while(bl >= 0){ sum = (int)(b.charAt(bl)-'0') + carries; res = String.valueOf(sum%2) + res; carries = sum/2; bl--; } if(carries == 1){ res = "1" + res; } //System.out.println("a<b的字符串:"+res); return res; } } }