LeetCode 67. Add Binary

文章目录

    • 一、题目
    • 二、题解

一、题目

Given two binary strings a and b, return their sum as a binary string.

Example 1:

Input: a = “11”, b = “1”
Output: “100”
Example 2:

Input: a = “1010”, b = “1011”
Output: “10101”

Constraints:

1 <= a.length, b.length <= 104
a and b consist only of ‘0’ or ‘1’ characters.
Each string does not contain leading zeros except for the zero itself.

二、题解

模拟二进制加法过程即可

class Solution {
public:
    string addBinary(string s1, string s2) {
        int len1 = s1.length();
        int len2 = s2.length();
        int c = 0;
        int i = len1 - 1,j = len2 - 1;
        string res = "";
        while(i >= 0 && j >= 0){
            int a = s1[i] - '0';
            int b = s2[j] - '0';
            int r = a + b + c;
            if(r > 1) c = 1,r = r % 2;
            else c = 0;
            res += to_string(r);
            i--,j--;
        }
        while(i >= 0){
            int a = s1[i] - '0';
            int r = a + c;
            if(r > 1) c = 1,r = r % 2;
            else c = 0;
            res += to_string(r);
            i--;
        }
        while(j >= 0){
            int b = s2[j] - '0';
            int r = b + c;
            if(r > 1) c = 1,r = r % 2;
            else c = 0;
            res += to_string(r);
            j--;
        }
        if(c > 0) res += to_string(1);
        reverse(res.begin(),res.end());
        return res;
    }
};

你可能感兴趣的:(leetcode,算法,数据结构,c++,位运算)