[LeetCode][Java] Add Binary

本文介绍了一个用于计算两个二进制字符串和的算法,包括字符串填充、进位处理及最终结果转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

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

题意:

给定两个二进制字符,返回他们的和

比如,

a = "11"
b = "1"
Return "100".

算法分析:

填充两个字符串中较短的,之后注意进位的问题,没什么特别的。


AC代码:

public class Solution 
{
    public  String addBinary(String a, String b) 
    {
    	if(a.length()==0) return b;
    	if(b.length()==0) return a;
    	if(a.equals("0"))  return b;
    	if(b.equals("0"))  return a;
    	int i=0;
    	int j=0;
    	int newplus=0;
    	String res="";
    	String newa="";
    	String newb="";
    	String finalres="";
    	int maxlength;
    	maxlength=Math.max(a.length(), b.length());
    	//用‘0’填充a或者b,使其长度相等
    	if(a.length()>b.length())
    	{
    		for(i=0;i<a.length()-b.length();i++)
    		{
    			newb+='0';
    		}
    		for(i=0;i<b.length();i++)
    			newb+=b.charAt(i);
    		newa=a;
    	}
    	else if(b.length()>a.length())
    	{
    		for(i=0;i<b.length()-a.length();i++)
    		{
    			newa+='0';
    		}
    		for(i=0;i<a.length();i++)
    			newa+=a.charAt(i);
    		newb=b;
    	}
    	else
    	{
    	    newa=a;
    	    newb=b;
    	}
    	maxlength=Math.max(newa.length(), newb.length());
		int plus=0;
		int tem=0;
    	for(i=maxlength-1;i>=0;i--)
		{
			if(newa.charAt(i)=='1'&&newb.charAt(i)=='1')
			{
				tem=0+plus;
			    plus=1;
				if(i==0)
				{
					newplus=1;
					maxlength++;
				}
			}
			else if(newa.charAt(i)=='0'&&newb.charAt(i)=='0')
			{
    			tem=0+plus;
    			plus=0;
			}
    		else 
    		{
    			tem=1+plus;
    			if(tem==2) 
				{
    				tem=0;
    				plus=1;
    				if(i==0)
    				{
    					newplus=1;
    					maxlength++;
    				}
				}
    		}
    		res+=Integer.toString(tem);
		}
    	if(newplus==1) res=res+'1';
    	for(i=res.length()-1;i>=0;i--)
    		finalres+=res.charAt(i);
		return finalres;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值