[LeetCode] Add Binary

本文详细介绍了如何解决LeetCode上的Add Binary问题,通过模拟加法操作,实现两个二进制字符串的加法。作者提供了一个C++实现方案,包括处理进位、去除前导零等细节。

https://leetcode.com/problems/add-binary/

模拟加法操作,链表也有类似的问题(Add Two Numbers)。

/*
 * author : TK
 * date   : 2017-02-14
 * problem: LeetCode 67: Add Binary
 * method : simulate the operation of addition
 */ 
class Solution {
public:
    string addBinary(string a, string b) {
        int p1 = a.size() - 1, p2 = b.size() - 1, carry = 0;
        
        // simulate the addition operation
        string ret = "";
        while (true) {
            if (p1 >= 0) carry += (a[p1--] - '0');
            if (p2 >= 0) carry += (b[p2--] - '0');
            string next_digit = to_string(carry % 2);
            carry /= 2;
            if (p1 >= 0 || p2 >= 0 || carry != 0 || next_digit != "0") {
                ret = next_digit + ret;
            } else break;
        }
        
        // remove the prefix '0'
        int i = 0;
        while (i < ret.size()) {
            if (ret[i] != '0') break;
            i++;
        }
        if (ret.empty()) ret = "0";
        
        return ret.substr(i, ret.size() - i);
    }
};

转载于:https://www.cnblogs.com/ilovezyg/p/6403613.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值