Add Binary

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();
        
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值