模拟题---Leetcode67---二进制求和

题目

  给你两个二进制字符串,返回它们的和(用二进制表示)。输入为 非空 字符串且只包含数字 1 和 0。

示例 1:
输入: a = “11”, b = “1”
输出: “100”

示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”

语言:C++
外部依赖:单元测试库-gtest
规范:需要自己写单元测试类,来进行提交前的测试,减少重复工作,并且对非法输入进行过滤

详解:
  逻辑就是从字符串的最后一位开始遍历,将两个字符串取出来的字符以及上一个进位进行相加,获得下一个进位以及当前下标的数据。如果此时的下标超过了其中一个字符串的长度,那就设当前字符串下标上的取得的数据为0,当下标超过两个字符串的最长位数,停止循环。

#include<iostream>
#include<stack>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
using namespace std;


namespace slution{
    //输入为 非空 字符串且只包含数字 1 和 0
    class Solution {
    public:
        string addBinary(string a, string b) {
            //miniLen代表两个字符串中最短的长度 采用驼峰命名法
            //相加无非三种情况 0+0=0 1+0=1 1+1=0 进一位
            int cnt = 1;
            int c = 0;
            int aLen = a.size();
            int bLen = b.size();
            int tmpA,tmpB;
            string result = "";
            //当遍历的长度没有达到长字符串的长度时候 继续遍历
            while(cnt<=aLen||cnt<=bLen){
                //取当前字符串的字符
                if(cnt<=aLen){
                    tmpA = a[aLen-cnt] - '0';
                }else{
                    tmpA = 0;
                }
                if(cnt<=bLen){
                    tmpB = b[bLen-cnt] - '0';
                }else{
                    tmpB = 0;
                }
                char tmp = (tmpA+tmpB+c)%2 + '0';
                c = (tmpA+tmpB+c)/2;
                result = tmp+result;
                cnt++;
            }
            //如果最后的进位是1 那么在字符串前后添加1
            if(c==1)
                result = "1" + result;
            return result;
        }
    };
}
#include<cstdio>
#include<gtest/gtest.h>
#include "solution.h"
using namespace slution;

//单元测试
Solution slu;

TEST(slutiontest, HandleNormalInput)
{

    string input1 = "110";
    string input2 = "1";
    string output1 = "111";
    EXPECT_EQ(output1, slu.addBinary(input1,input2));

    input1 = "11";
    input2 = "1";
    output1 = "100";
    EXPECT_EQ(output1, slu.addBinary(input1,input2));

    input1 = "1010";
    input2 = "1011";
    output1 = "10101";
    EXPECT_EQ(output1, slu.addBinary(input1,input2));

}

TEST(slutiontest, HandleExtremeInput)
{
    string input1 = "0";
    string input2 = "0";
    string output1 = "0";
    EXPECT_EQ(output1, slu.addBinary(input1,input2));
}

int main(int argc, char *argv[])
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
    return 0;
}

结果

执行结果:
通过
显示详情
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:7.1 MB, 在所有 C++ 提交中击败了100.00%的用户

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值