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

二进制求和(LintCode)

时间:2015-12-05 19:24:03      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

二进制求和

给定两个二进制字符串,返回他们的和(用二进制表示)。

样例

a = 11

b = 1

返回 100

 

细节出了好多问题,提交了好多次。。。

技术分享
 1 public class Solution {
 2     /**
 3      * @param a a number
 4      * @param b a number
 5      * @return the result
 6      */
 7     public String addBinary(String a, String b) {
 8         int c = 0;
 9         int al = a.length() - 1;
10         int bl = b.length() - 1;
11         
12         String s = "";
13         for(;al >= 0 && bl >= 0;al--,bl--) {
14             int ax = Integer.valueOf(a.substring(al,al + 1)).intValue();
15             int bx = Integer.valueOf(b.substring(bl,bl + 1)).intValue();
16             s = (ax + bx + c) % 2 + s;
17             c = (ax + bx + c) / 2;
18         }
19         
20         if(bl >= 0) {
21             while(bl != -1) {
22                 int x = Integer.valueOf(b.substring(bl,bl + 1)).intValue();
23                 s = (c + x) % 2 + s;
24                 c = (c + x) / 2;
25                 bl--;
26             }
27         }
28         
29         if(al >= 0) {
30             while(al != -1) {
31                 int x = Integer.valueOf(a.substring(al,al + 1)).intValue();
32                 s = (c + x) % 2 + s;
33                 c = (c + x) / 2;
34                 al--;
35             }
36         }
37         
38         if(c != 0) {
39             s = c + s;
40         }
41         
42         return s;
43     }
44 }
View Code

 

二进制求和(LintCode)

标签:

原文地址:http://www.cnblogs.com/FJH1994/p/5022059.html

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