每日算法题:19.7.25

本文介绍了一种处理二进制字符串相加的算法实现,通过反转字符串并逐位进行加法运算,同时处理进位,最终得到二进制表示的和。此算法适用于非空且仅包含1和0的字符串输入。

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

题目:

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0。

示例:

输入: a = "1010", b = "1011"

输出: "10101"

代码:

public class Test17 {
    public String addBinary(String a, String b) {
        char[] temp1 = new StringBuilder(a).reverse().toString().toCharArray();
        char[] temp2 = new StringBuilder(b).reverse().toString().toCharArray();
        int index =0;
        int last = 0;
        String result="";
        while(index<temp1.length && index<temp2.length){
            int i = Integer.parseInt(String.valueOf(temp1[index]));
            int j = Integer.parseInt(String.valueOf(temp2[index]));
            if (i+j+last==0) {
                result ="0"+result;
            }else if(i+j+last==1){
                result = "1"+result;
                last=0;
            }else if(i+j+last==2){
                result ="0"+result;
                last = 1;
            }else{
                result ="1"+result;
                last = 1;
            }
            index++;
        }

        if (index<temp1.length) {
            while(index<temp1.length){
                int j = Integer.parseInt(String.valueOf(temp1[index]));
                if (j+last==0) {
                    result ="0"+result;
                }else if(j+last==1){
                    result = "1"+result;
                    last=0;
                }else if(j+last==2){
                    result ="0"+result;
                    last = 1;
                }else{
                    result ="1"+result;
                    last = 1;
                }
                index++;
            }
        }else if(index<temp2.length){
            while(index<temp2.length){
                int j = Integer.parseInt(String.valueOf(temp2[index]));
                if (j+last==0) {
                    result ="0"+result;
                }else if(j+last==1){
                    result = "1"+result;
                    last=0;
                }else if(j+last==2){
                    result ="0"+result;
                    last = 1;
                }else{
                    result ="1"+result;
                    last = 1;
                }
                index++;
            }
        }

        if (last==1) {
            result = "1"+result;
        }

        return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值