[LeetCode] Add Binary

本文详细介绍了如何使用C++实现二进制数相加的功能,包括字符串操作、位运算以及进位处理,通过逐步解析示例代码帮助理解算法细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The idea is to add the two binary numbers (represented as strings) from back to forth bit by bit and store the result in the longer string. After the shorter string has been added, we continue to handle the carry bit. We may need to append the carry bit to the beginning of the longer string if necessary.

The code is as follows.

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         int m = a.length(), n = b.length(), c = 0, i, j;
 5         if (m < n) return addBinary(b, a);
 6         for (i = m - 1, j = n - 1; j >= 0; i--, j--) {
 7             int ad = a[i] - '0', bd = b[j] - '0';
 8             a[i] = (ad ^ bd ^ c) + '0';
 9             c = (ad + bd + c >= 2);
10         }
11         for (; i >= 0; i--) {
12             int ad = a[i] - '0';
13             a[i] = (ad ^ c) + '0';
14             c = (ad + c >= 2);
15         }
16         if (c) a = '1' + a;
17         return a; 
18     }
19 };

Running the above code on the simple example a = "1", b = "11" will help you get all its details (both the two for loops and the two if statements will be hit) :-)

转载于:https://www.cnblogs.com/jcliBlogger/p/4733458.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值