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

    }
}
相关推荐
知星小度S2 小时前
系统核心解析:深入操作系统内部机制——进程管理与控制指南(一)【进程/PCB】
linux·运维·服务器·进程
编码浪子5 小时前
趣味学RUST基础篇(异步)
服务器·rust·负载均衡
码农101号6 小时前
运维安全05 - iptables规则保存与恢复
运维·网络·安全
Empty_7776 小时前
SELinux安全上下文
linux·服务器·安全
bug攻城狮7 小时前
解决Ubuntu中apt-get -y安装时弹出交互提示的问题
linux·运维·ubuntu
夜阑珊夭夭8 小时前
linux自定义网卡名字
linux·运维
佛天华8 小时前
centos 时间校准
linux·运维·centos
小柯J桑_9 小时前
Linux:线程封装
linux·运维·c++
zwhSunday9 小时前
Linux驱动开发(1)概念、环境与代码框架
linux·运维·驱动开发