首页 > 其他 > 详细

[leetcode]Add Binary

时间:2014-07-24 22:57:23      阅读:327      评论:0      收藏:0      [点我收藏+]

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 }

[leetcode]Add Binary,布布扣,bubuko.com

[leetcode]Add Binary

原文:http://www.cnblogs.com/huntfor/p/3866502.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!