Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100”
.
public class Solution {
public String addBinary(String a, String b) {
}
}
解析:
ab字符串都是二进制的数字0.1 。返回两个二进制数字的和。
解法:
1,首先将2个字符串从左到右依次读取并入2个栈。
2,一个临时变量保存每次加法的进位。
3,从2个栈中pop2个值。然后相加,压入另一个栈,如果有进位,纪录。
4,最后得到的新的结果栈,就是结果了。
public class Solution {
public String addBinary(String a, String b) {
Stack<Integer> A= new Stack<Integer>();
Stack<Integer> B= new Stack<Integer>();
Stack<Integer> Result= new Stack<Integer>();
int temp=0;int plus=0;
StringBuffer sb= new StringBuffer();
for(int i =0;i<a.length();i++){
A.push(Integer.parseInt(String.valueOf(a.charAt(i))));
}
for(int i =0;i<b.length();i++){
B.push(Integer.parseInt(String.valueOf(b.charAt(i))));
}
while(!A.isEmpty()||!B.isEmpty()){
if(A.isEmpty()) plus=B.pop()+temp;
else if(B.isEmpty()) plus=A.pop()+temp;
else plus=A.pop()+B.pop()+temp;
temp=0;
if(plus==3){Result.push(1); temp=1;}
else if(plus==2){Result.push(0); temp=1;}
else if(plus==1) Result.push(1);
else Result.push(0);
}
if(temp==1) Result.push(1);
int size=Result.size();
for(int i=0;i<size;i++){
sb.append(String.valueOf(Result.pop()));
}
return sb.toString();
}
}