二进制求和 - 简单

*************

C++

topic: 67. 二进制求和 - 力扣(LeetCode)

*************

Give the topic an inspection.

|----------------------------------------------------------------------------|
| |

Too many works these days. And no spare time for code learning. However here I am gagin.

This topic is an easy one and I want to practice some skills about namespace, class and so on. So todays study might have some fun.

binary is every, it is something like to be or not to be. It just has 0 and 1.

|----------------------------------------------------------------------------|
| |
| 自己动手制作计算机CPU的核心部件,二进制加法器 |

so the code is really to say.

first to get the size and define a string to store the sumation. Adding another single bit need int carry help.

cpp 复制代码
class Solution {
public:
    string addBinary(string a, string b) {
        string result; // 存储最终结果的二进制字符串
        int i = a.size() - 1; // 指针i初始指向字符串a的最后一个字符(最低位)
        int j = b.size() - 1; // 指针j初始指向字符串b的最后一个字符(最低位)
        int carry = 0; // 进位标志,初始化为0

        // 循环条件:当任意一个字符串还有未处理的位,或者还有进位需要处理时继续
        while (i >= 0 || j >= 0 || carry > 0) {
            // 获取当前位的数字,如果指针已越界则补0
            int digitA = (i >= 0) ? (a[i] - '0') : 0; // 将字符转换为数字('0'->0, '1'->1)
            int digitB = (j >= 0) ? (b[j] - '0') : 0; // 同上

            // 计算当前位的总和(包括进位)
            int sum = digitA + digitB + carry;
            
            // 计算新的进位(二进制逢2进1)
            carry = sum / 2; // 如果sum>=2则carry=1,否则carry=0
            
            // 计算当前位的值(取sum对2的余数)
            int currentDigit = sum % 2; // 结果为0或1
            
            // 将当前位的结果存入result(注意这里是从低位到高位顺序存储的)
            result.push_back(currentDigit + '0'); // 将数字转换回字符格式
            
            // 移动指针到前一位
            i--; // 处理a的前一位
            j--; // 处理b的前一位
        }

        // 由于我们是先计算低位后计算高位,需要反转字符串得到正确顺序
        reverse(result.begin(), result.end());
        
        // 返回最终结果
        return result;
    }
};

take an example: a = "1", b = "1"(即 1 + 1,二进制结果应为 "10"

步骤 当前执行代码行 变量状态变化 (i, j, carry, result) 条件判断结果 循环次数 输出内容 操作注释
1 string a = "1"; a = "1" - - - 初始化输入 a
2 string b = "1"; b = "1" - - - 初始化输入 b
3 string result; result = "" - - - 初始化空结果
4 int i = a.size()-1; i = 0 - - - 指向 a 的最后一位 ('1')
5 int j = b.size()-1; j = 0 - - - 指向 b 的最后一位 ('1')
6 int carry = 0; carry = 0 - - - 初始化进位为 0
7 `while (i >= 0 j >= 0 carry > 0)` i=0, j=0, carry=0进入循环
8 int digitA = (i >= 0) ? (a[i]-'0') : 0; digitA = 1 (a[0]='1' → 1) i >= 0true 1 - a 的当前位 '1' 并转为数字 1
9 int digitB = (j >= 0) ? (b[j]-'0') : 0; digitB = 1 (b[0]='1' → 1) j >= 0true 1 - b 的当前位 '1' 并转为数字 1
10 int sum = digitA + digitB + carry; sum = 1 + 1 + 0 = 2 - 1 - 计算当前位和进位总和
11 carry = sum / 2; carry = 0 → **1** - 1 - 更新进位:2 / 2 = 1
12 int currentDigit = sum % 2; currentDigit = 0 (2 % 2 = 0) - 1 - 计算当前位值:0
13 result.push_back(currentDigit + '0'); result = "" → **"0"** - 1 - '0' 存入 result
14 i--; j--; i = 0 → **-1**, j = 0 → -1 ` - 1 - 移动指针到前一位(越界)
15 `while (i >= 0 j >= 0 carry > 0)` i=-1, j=-1, carry=1进入循环
16 int digitA = (i >= 0) ? (a[i]-'0') : 0; digitA = 0 (i < 0) i >= 0false 2 - a 已越界,补 0
17 int digitB = (j >= 0) ? (b[j]-'0') : 0; digitB = 0 (j < 0) j >= 0false 2 - b 已越界,补 0
18 int sum = digitA + digitB + carry; sum = 0 + 0 + 1 = 1 - 2 - 计算当前位和进位总和
19 carry = sum / 2; carry = 1 → **0** - 2 - 更新进位:1 / 2 = 0
20 int currentDigit = sum % 2; currentDigit = 1 (1 % 2 = 1) - 2 - 计算当前位值:1
21 result.push_back(currentDigit + '0'); result = "0" → **"01"** - 2 - '1' 存入 result
22 i--; j--; i = -1 → **-2** , j = -1 → -2` - 2 - 移动指针(越界)
23 `while (i >= 0 j >= 0 carry > 0)` i=-2, j=-2, carry=0退出循环
24 reverse(result.begin(), result.end()); result = "01" → **"10"** - - - 反转结果字符串
25 return result; - - - "10" 返回最终结果 "10"

and the function is in class Solution, what if I put the calculation function in class calculationBinary?

cpp 复制代码
// 专门负责二进制计算逻辑的类
class CalculationBinary 
{
public:
    string add(string a, string b) 
    {
        string result;
        int i = a.size() - 1;  // 指向a的末位(最低位)
        int j = b.size() - 1;  // 指向b的末位(最低位)
        int carry = 0;         // 进位标志

        // 当任意数字还有未处理的位或存在进位时继续
        while (i >= 0 || j >= 0 || carry > 0) 
        {
            // 获取当前位数字(越界补0)
            int digitA = (i >= 0) ? (a[i--] - '0') : 0;
            int digitB = (j >= 0) ? (b[j--] - '0') : 0;
            
            // 计算当前位总和及进位
            int sum = digitA + digitB + carry;
            carry = sum / 2;           // 计算新进位
            result.push_back((sum % 2) + '0');  // 存储当前位
        }
        
        // 反转得到高位优先的顺序
        reverse(result.begin(), result.end());
        return result;
    }
};


// 对外提供的接口类
class Solution {
public:
    string addBinary(string a, string b) 
    {
        CalculationBinary calculator;  // 创建计算器实例
        return calculator.add(a, b);   // 调用计算方法
    }
};
相关推荐
cdut_suye9 分钟前
【Linux系统】从零开始构建简易 Shell:从输入处理到命令执行的深度剖析
java·linux·服务器·数据结构·c++·人工智能·python
-qOVOp-11 分钟前
zst-2001 历年真题 设计模式
java·算法·设计模式
yaoshengvalve26 分钟前
V型球阀材质性能深度解析:专攻颗粒、料浆与高腐蚀介质的工业利器-耀圣
开发语言·网络·数据结构·c++·安全·材质
evolution_language27 分钟前
LintCode第68题-二叉树的前序遍历,第67题-二叉树的后序遍历
数据结构·算法·新手必刷编程50题
passionSnail38 分钟前
《用MATLAB玩转游戏开发:从零开始打造你的数字乐园》基础篇(2D图形交互)-俄罗斯方块:用旋转矩阵打造经典
算法·matlab·矩阵·游戏程序·交互
yxc_inspire39 分钟前
C++STL在算法竞赛中的应用详解
c++·算法·stl
James. 常德 student42 分钟前
leetcode-hot-100(哈希)
算法·leetcode·哈希算法
金融小师妹1 小时前
量化解析美英协议的非对称冲击:多因子模型与波动率曲面重构
大数据·人工智能·算法
是店小二呀1 小时前
【算法-哈希表】常见算法题的哈希表套路拆解
数据结构·c++·算法·散列表
jiunian_cn1 小时前
【c++】多态详解
java·开发语言·数据结构·c++·visual studio