【LeetCode】Add Binary

版权声明: https://blog.csdn.net/ysq96/article/details/90170079

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

题意:实现二进制加法

C++:

class Solution {
public:
    string addBinary(string a, string b) {
        int len_a = a.length()-1,len_b = b.length()-1,carry = 0;
        string res="";
        while(len_a>=0||len_b>=0){
            int m = len_a>=0?a[len_a--]-'0':0;
            int n = len_b>=0?b[len_b--]-'0':0;
            int sum = m + n + carry;
            res = to_string(sum%2)+res;
            carry = sum/2;
        }
        if(carry>0)res="1"+res;
        return res;
    }
};

Python3:

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return bin(int(a, 2) + int(b, 2))[2:]

猜你喜欢

转载自blog.csdn.net/ysq96/article/details/90170079