首页 > 代码库 > [leetcode]Add Binary
[leetcode]Add Binary
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a ="11"
b ="1"
Return"100"
.
算法思路:
模拟二进制加法,跟十进制木有区别,将a,b转置(不转置的话,倒着遍历也是同样道理),这样就可以从低位到高位逐级递加了
1 public class Solution { 2 public String addBinary(String a, String b) { 3 if( a == null || a.length() == 0) return b; 4 if( b == null || b.length() == 0) return a; 5 // assume that b.length is longer 6 if(b.length() < a.length()) return addBinary(b, a); 7 StringBuilder br = new StringBuilder(b).reverse(); 8 StringBuilder ar = new StringBuilder(a).reverse(); 9 int leap = 0;10 for(int i = 0; i < br.length(); i++){11 int aNum = (i < ar.length())? (ar.charAt(i) == ‘0‘ ? 0 : 1) : 0;12 int bNum = br.charAt(i) == ‘0‘ ? 0 : 1;13 if(aNum + bNum + leap == 1){14 br.setCharAt(i, ‘1‘);15 leap = 0;16 }else if(aNum + bNum + leap == 2){17 br.setCharAt(i, ‘0‘);18 leap = 1;19 }else if(aNum + bNum + leap == 3){20 br.setCharAt(i, ‘1‘);21 leap = 1;22 }23 }24 if(leap == 1) br.append(‘1‘);25 return br.reverse().toString();26 }27 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。