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

Add Binary

时间:2015-05-06 06:49:57      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/add-binary/

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

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

 1 import java.util.Stack;
 2 
 3 
 4 public class Solution {
 5     public static String addBinary(String a, String b) {
 6     Stack<Integer> st=new Stack();
 7     int lena=a.length();int lenb=b.length();
 8     String comp="";
 9     for(int i=0;i<Math.abs(lena-lenb);i++){comp+=‘0‘;}
10     int len;
11     if(lena<lenb){a=comp+a;len=lenb;}
12     else{b=comp+b;len=lena;}
13     int jin=0;
14     for(int i=len-1;i>=0;i--){
15         char x=a.charAt(i);char y=b.charAt(i);
16         int res=x-‘0‘+y-‘0‘+jin;
17         if(res>=2){jin=1;res-=2;}
18         else{jin=0;}
19         st.add(res);
20     }
21     if(jin==1){st.add(jin);}
22     String t="";
23     while(!st.isEmpty()){
24         t+=st.pop();
25     }
26     return t;
27     }
28     public static void main(String[]args){
29     System.out.println(addBinary("110","11"));
30     }
31 }

 

Add Binary

标签:

原文地址:http://www.cnblogs.com/qq1029579233/p/4480782.html

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