[Leecode 67] Add Binary Solution

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

For example,
a = "11"
b = "1"
Return "100".

This question has several issues need to be pay attention. 

1. Add the value from right to left.

2. Carry bit can exist after the sum is over 2, in particularly, it can exist after all digits added together

The idea is same as decimalism(十进制)

class Solution {
public:
    string addBinary(string a, string b) {
        if(a.size() == 0) return b;
        if(b.size() == 0) return a;
        
        string result;
        int length = max(a.size(), b.size());
        //add '0' before the front of the short string
        int dif = a.size() - b.size();
        
        string c = "";
        for(int i = 0; i < abs(dif); i++)
        {
            c += '0';
        }
        
        string na;
        string nb;
        if(dif >= 0)
        {
            nb = c + b;
            result = AddBinaryEqual(a, nb, length);
        }
        else
        {
            na = c + a;
            result = AddBinaryEqual(na, b, length);
        }
        
        return result;
    }
    
    private: 
        string AddBinaryEqual(string x, string y, int size)
        {
            int count = 0;
            int sum = 0;
            string result = "";
            for(int i = size - 1; i >= 0; i--)
            {
                sum = (x[i] - '0') + (y[i] - '0') + count; // 0, 1, 2, 3
                char c = sum % 2 + '0';
                result = c + result ;
                if(sum >= 2){
                    count = 1;
                }else{
                    count = 0;
                }
            }
            
            if(count == 1)
                result = '1' + result;
        
            return result;
        }
    
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值