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

*Add Binary

时间:2015-09-11 08:00:35      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
 
 
 
 1     public String addBinary(String a, String b) {
 2         if (a==null ||a.length()==0){
 3             return b;
 4         }
 5         
 6         if (b==null || b.length()==0){
 7             return a;
 8         }
 9         
10        StringBuilder sb=new StringBuilder();
11        
12         
13         int lastA=a.length()-1;
14         int lastB=b.length()-1;
15         int carry=0;
16         
17         
18         while (lastA>=0 ||lastB>=0 ||carry>0){
19             int num1=lastA>=0?a.charAt(lastA--)-‘0‘:0;
20             int num2=lastB>=0?b.charAt(lastB--)-‘0‘:0;
21             int current=(num1+num2+carry)%2;
22             carry=(num1+num2+carry)/2;
23             
24             sb.insert(0, current);
25             
26             
27         }
28         
29         return sb.toString();
30     }

 

 
reference: http://rleetcode.blogspot.com/2014/02/add-binary-java.html

*Add Binary

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4799856.html

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