leetcode Add Binary

本文介绍了一种解决二进制字符串相加问题的方法。通过遍历两个输入字符串并逐位进行二进制加法运算,同时处理进位的情况,最终得到正确的二进制和。该方法适用于计算机科学领域的初学者学习二进制运算。

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

For example,
a = "11"
b = "1"

Return "100".

题目本身还是比较简单的,就是二进制加法,不过写程序的时候发现自己对字符串的api还是有点生疏,贴出来以便复习用吧~注意一下进位的取值就可以了。

public String addBinary(String a, String b) {
    String res=new String();
    int exceed = 0;
    int bits=0;
    int indexa = a.length() - 1, indexb = b.length() - 1;
    while (indexa >= 0 && indexb >= 0) {
        int result = a.charAt(indexa)-'0'+b.charAt(indexb)-'0'+exceed;
        bits=result%2;
        exceed=result/2;
        res=""+bits+""+res;
        indexa--;
        indexb--;
    }
    while(indexa>=0) {
        int result = exceed + a.charAt(indexa)-'0';
        bits=result%2;
        exceed=result/2;
        res=""+bits+""+res;
        indexa--;
    }
    while(indexb>=0) {
        int result = exceed + b.charAt(indexb)-'0';
        bits=result%2;
        exceed=result/2;
        res=""+bits+""+res;
        indexb--;
    }
    if(exceed==1)
        res=""+exceed+""+res;
    StringBuffer str=new StringBuffer();
    return res;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值