LCR 002. 二进制求和

剑指Offer通关

力扣搜索LCR即为剑指Offer的所有题目。

LCR 002. 二进制求和

笨方法:

先将两个string反过来,然后相加。

然后将剩下的长的再补上。

需要注意进位。

java 复制代码
class Solution {
    public String addBinary(String a, String b){
        StringBuffer res = new StringBuffer();
        StringBuffer c = new StringBuffer(a).reverse();
        StringBuffer d = new StringBuffer(b).reverse();
        String Long = c.length()>d.length() ? c.toString() : d.toString();
        int len = Math.min(a.length(), b.length());
        int idx = 0;
        int add = 0;
        for(idx=0;idx<len;idx++){
            if(c.charAt(idx)=='0' && d.charAt(idx)=='0'){
                if(add==0)
                    res.append("0");
                else if(add==1){
                    res.append("1");
                    add = 0;
                }
            }

            else if(c.charAt(idx)=='1' && d.charAt(idx)=='1'){
                if(add == 0){
                    res.append("0");
                    add = 1;
                }
                else if(add == 1){
                    res.append("1");
                    add = 1;
                }
            }
            else{
                if(add==0){
                    res.append("1");
                    add = 0;
                }
                else if(add==1){
                    res.append("0");
                    add = 1;
                }
            }
        }
        for(; idx<Long.length();idx ++){
            if(add == 0)
                res.append(Long.charAt(idx));
            else{
                if(Long.charAt(idx) == '0'){
                    res.append('1');
                    add = 0;
                }
                else res.append('0');
            }
        }
        if(add == 1)
            res.append("1");
        return res.reverse().toString();

    }
}
相关推荐
China_Yanhy1 小时前
我的区块链运维日记 · 第 4 日:死掉的“活”节点 —— 攻克“同步滞后(Lag)”
运维·区块链
kida_yuan1 小时前
【Linux】说说我对 Wine 与 deepin-wine 的理解
linux·运维·wine
松涛和鸣2 小时前
DAY63 IMX6ULL ADC Driver Development
linux·运维·arm开发·单片机·嵌入式硬件·ubuntu
扑火的小飞蛾2 小时前
RHEL 7 安装 Docker 过程总结
运维·docker·容器
程序员_大白2 小时前
区块链部署与运维,零基础入门到精通,收藏这篇就够了
运维·c语言·开发语言·区块链
德迅云安全—珍珍2 小时前
2核2G的云服务器可以架设游戏吗?
运维·服务器·游戏
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.3 小时前
HAProxy状态页:运维监控实战指南
运维
陈聪.4 小时前
HRCE实验
运维
Miracle&4 小时前
在Linux VirtualBox中安装系统失败
linux·运维·服务器
ShoreKiten4 小时前
ctfshow-web316
运维·服务器·前端