67. Add Binary 二进制加法leetcode

67 Add Binary 二进制加法leetcode

题目描述

Given two binary strings a and b, return their sum as a binary string.
中文:给定两个二进制的字符串,计算他们的加法和,结果以字符串返回

知识点:
1.字符转数字:该字符 - ‘0’
2.二进制加法
3.进位处理

方法1:

思路:将短字符串前面补零,从后往前对应相加,
二进制加法:
1+1=10,1+1+1=11
十进制加法:
结果有四种情况:0、1、2、3 后两种需要将进位标志设置为1.

class Solution {
public:
    string addBinary(string a, string b) {
            int a_len = a.size();
            int b_len = b.size();
            string re="";
            if(a_len > b_len)
            {
                for(int i=0;i<a_len-b_len;i++)
                {
                    b = '0' + b;
                }
            }else{
                for(int i=0;i<b_len-a_len;i++)
                {
                    a = '0' + a;
                }
            }
            int carry = 0;
            for(int j=a.size()-1;j>=0;j--)
            {
                int tmp;
                tmp = (a[j]-'0')+(b[j]-'0')+carry;
                if(tmp == 0)
                {
                    re = '0' + re;
                    carry = 0;
                }
                if(tmp == 1)
                {
                    re = '1' + re;
                    carry = 0;
                }
                if(tmp == 2)
                {
                    re = '0' + re;
                    carry = 1;
                }
                if(tmp == 3)
                {
                    re = '1' + re;
                    carry = 1;
                }
            }
            if(carry)
            {
                re = '1' + re;
            }
            return re;
        }
};

方法2:

这种方法就是使用数组,从后往前遍历,不齐补零,商表进位,余数表示相加结果值;

class Solution {
public:
    string addBinary(string a, string b) {
        int a_len = a.size()-1;
        int b_len = b.size()-1;
        string re = "";
        int carry = 0;
        while(a_len>=0 || b_len>=0)
        {
            int p_a = a_len>=0? a[a_len--]-'0':0;
            int p_b = b_len>=0? b[b_len--]-'0':0;
            int sum = p_a + p_b + carry;
            carry = sum / 2;
            re = to_string(sum%2) + re;
        }
        return carry==1?"1"+re:re;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值