leetCode67. 二进制求和

leetCode67. 二进制求和

题目思路:


cpp 复制代码
class Solution {
public:
    string addBinary(string a, string b) {
        reverse(a.begin(),a.end());
        reverse(b.begin(),b.end());

        string res;
        // 这三个条件,遵循短路原则,i<a.size()不成立,看i<b.size()不成立,若t为0才退出,防止t=1没有来的及处理
        for(int i = 0, t = 0; i < a.size() || i < b.size() || t; i++){
            if(i < a.size()) t += a[i] - '0';
            if(i < b.size()) t += b[i] - '0';
            res += to_string(t % 2);
            t /= 2;
        }

        reverse(res.begin(), res.end());

        return res;
    }
};
相关推荐
杰杰批6 小时前
力扣热题100——矩阵
算法·leetcode·矩阵
一叶祇秋12 小时前
Leetcode - 周赛446
算法·leetcode·职场和发展
rigidwill66612 小时前
LeetCode hot 100—分割等和子集
数据结构·c++·算法·leetcode
JPC客栈14 小时前
LeetCode面试经典 150 题(Java题解)
java·leetcode·面试
冠位观测者15 小时前
【Leetcode 每日一题】781. 森林中的兔子
数据结构·算法·leetcode
@蓝莓果粒茶18 小时前
LeetCode第158题_用Read4读取N个字符 II
前端·c++·python·算法·leetcode·职场和发展·c#
旷野本野20 小时前
【LeetCode】嚼烂热题100【持续更新】
算法·leetcode
一杯咖啡Miracle1 天前
代码随想录算法训练营第三十五天|416. 分割等和子集、698.划分为k个相等的子集、473.火柴拼正方形
数据结构·python·算法·leetcode
刃神太酷啦1 天前
栈和队列--数据结构初阶(2)(C/C++)
c语言·数据结构·c++·算法·leetcode
王齐家04061 天前
每日一题算法——移除链表元素、反转链表
数据结构·算法·leetcode·链表