leetcode 64 add binary

Posted JamieHou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 64 add binary相关的知识,希望对你有一定的参考价值。

题目

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"
Constraints:
Each string consists only of \'0\' or \'1\' characters.
1 <= a.length, b.length <= 10^4
Each string is either "0" or doesn\'t contain any leading zero.

思路

代码

Code 01

class Solution {
public:
    string addBinary(string a, string b) {
        reverse(a.begin(),a.end()); //从低位开始处理
        reverse(b.begin(),b.end());
        string c;
        int r = 0; 
        int len = max(a.length(),b.length()); //取较大字符串长度
        for(int i=0;i<len;i++){
            r+=i<a.length()?a.at(i)==\'1\':0; //累加a中第i位的数字
            r+=i<b.length()?b.at(i)==\'1\':0; //累加b中第i位的数字
            c.push_back(r%2?\'1\':\'0\'); // 记录当前和数字
            r/=2; //更新当前余数
        }
        if(r!=0)c.push_back(\'1\'); //处理最高位进位
        reverse(c.begin(),c.end()); //存储为低位到高位,反转后为高位到低位
        return c;
    }
};

以上是关于leetcode 64 add binary的主要内容,如果未能解决你的问题,请参考以下文章

*Leetcode 67. Add Binary

leetcode add_binary 采坑记

leetcode67. Add Binary

leetcode Add Binary (easy) /java

leetcode第一刷_Add Binary

leetcode67. Add Binary