首页 > 其他 > 详细

[Leetcode] Add Binary

时间:2014-11-20 18:17:55      阅读:156      评论:0      收藏:0      [点我收藏+]

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

 

Solution:

 1 public class Solution {
 2     public String addBinary(String a, String b) {
 3         if(a==null)
 4             return b;
 5         if(b==null)
 6             return a;
 7         int end_a=a.length()-1;
 8         int end_b=b.length()-1;
 9         int carry=0;
10         String result="";
11         while(end_a>=0&&end_b>=0){
12             int temp=(a.charAt(end_a)-‘0‘)+(b.charAt(end_b)-‘0‘)+carry;
13             carry=temp/2;
14             temp%=2;
15             result=(temp+"")+result;
16             end_a--;
17             end_b--;
18         }
19         while(end_a>=0){
20             int temp=(a.charAt(end_a)-‘0‘)+carry;
21             carry=temp/2;
22             temp%=2;
23             result=(temp+"")+result;
24             end_a--;
25         }
26         while(end_b>=0){
27             int temp=(b.charAt(end_b)-‘0‘)+carry;
28             carry=temp/2;
29             temp%=2;
30             result=(temp+"")+result;
31             end_b--;
32         }
33         if(carry!=0){
34             result=(carry+"")+result;
35         }
36         return result;
37     }
38 }

 

[Leetcode] Add Binary

原文:http://www.cnblogs.com/Phoebe815/p/4110962.html

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