67. Add Binary

计算二进制

 

java:

 1 class Solution {
 2     public String addBinary(String a, String b) {
 3         int i = a.length()-1;
 4         int j = b.length()-1;
 5         char[] flag = {'0', '1'};
 6         int an = 0, bn = 0;
 7         char ac = '0', bc = '0';
 8         int carry = 0, bit_res = 0;
 9         StringBuilder res = new StringBuilder();
10         
11         while(i>=0||j>=0||carry!=0){
12             ac = i>=0?a.charAt(i):'0';
13             bc = j>=0?b.charAt(j):'0';
14             bit_res = carry+ ac-'0'+bc-'0';
15             res.insert(0, flag[bit_res%2]);
16             carry= bit_res / 2;
17             i--;
18             j--;
19         }
20         return res.toString();
21         
22     }
23 }

 

posted @ 2017-10-11 18:48  wilderness  阅读(132)  评论(0编辑  收藏  举报