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;
    }
};
相关推荐
CoderYanger9 小时前
递归、搜索与回溯-综合练习:19.目标和
java·算法·leetcode·1024程序员节
吃着火锅x唱着歌11 小时前
LeetCode 3185.构成整天的下标对数目II
算法·leetcode·职场和发展
资深web全栈开发11 小时前
LeetCode 1590:使数组和能被 p 整除(前缀和 + 哈希表优化)
算法·leetcode·前缀和·算法优化·哈希表·go 语言·取模运算
CoderYanger11 小时前
递归、搜索与回溯-综合练习:27.黄金矿工
java·算法·leetcode·深度优先·1024程序员节
sin_hielo12 小时前
leetcode 1590
数据结构·算法·leetcode
吃着火锅x唱着歌12 小时前
LeetCode 2748.美丽下标对的数目
数据结构·算法·leetcode
做怪小疯子12 小时前
LeetCode 热题 100——二叉树——二叉树的中序遍历
算法·leetcode·职场和发展
wyiyiyi12 小时前
【数据结构+算法】非递归遍历二叉树的理解
大数据·数据结构·笔记·算法·leetcode·数据分析
2401_8933266213 小时前
力扣1971.寻找图中是否存在路径
算法·leetcode·职场和发展