标签:
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 }
标签:
原文地址:http://www.cnblogs.com/qq1029579233/p/4480782.html