首页 > 其他 > 详细

*Add Binary

时间:2015-09-11 08:00:05      阅读:234      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!