[Kata 7 C++]Binary Addition

描述

Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.

The binary number returned should be a string.

Examples:(Input1, Input2 --> Output (explanation)))

1, 1 --> "10" (1 + 1 = 2 in decimal or 10 in binary)
5, 9 --> "1110" (5 + 9 = 14 in decimal or 1110 in binary)

测试用例

#include <random>
#include <string>
#include <tuple>
#include <cstdint>
#include <sstream>

Describe(FixedTests)
{
    It(should_pass_fixed_tests)
    {
        Assert::That(add_binary(1, 1), Equals("10"), ExtraMessage("Invalid result for a = 1, b = 1"));
        Assert::That(add_binary(0, 1), Equals("1"), ExtraMessage("Invalid result for a = 0, b = 1"));
        Assert::That(add_binary(1, 0), Equals("1"), ExtraMessage("Invalid result for a = 1, b = 0"));
        Assert::That(add_binary(2, 2), Equals("100"), ExtraMessage("Invalid result for a = 2, b = 2"));
        Assert::That(add_binary(51, 12), Equals("111111"), ExtraMessage("Invalid result for a = 51, b = 12"));
        Assert::That(add_binary(5, 9), Equals("1110"), ExtraMessage("Invalid result for a = 5, b = 9"));
        Assert::That(add_binary(10, 10), Equals("10100"), ExtraMessage("Invalid result for a = 10, b = 10"));
        Assert::That(add_binary(100, 100), Equals("11001000"), ExtraMessage("Invalid result for a = 100, b = 100"));
        Assert::That(add_binary(4096, 1), Equals("1000000000001"), ExtraMessage("Invalid result for a = 4096, b = 1"));
        Assert::That(add_binary(0, 2174483647), Equals("10000001100110111111110010111111"), ExtraMessage("Invalid result for a = 0, b = 2174483647"));
    }
  
    It(should_handle_edge_case)
    {
        Assert::That(add_binary(0, 0), Equals("0"), ExtraMessage("Invalid result for a = 0, b = 0"));
    }
};

Describe(RandomTests)
{
private:
    std::mt19937 engine{ std::random_device{}() };
    std::uniform_int_distribution<size_t> dist_l{ 0, 64 };
    std::uniform_int_distribution<char> dist_b{ 0, 1 };
  
    std::tuple<uint64_t, uint64_t, std::string> generate_problem()
    {        
        const size_t len = dist_l(engine);
        if(len == 0) return { 0, 0, "0" };
      
        std::string res = "1";
        uint64_t sum = 1;
      
        for(size_t i = 1; i < len; ++i)
        {
            const bool d = dist_b(engine);
            res += static_cast<char>(d + '0');
            sum = sum << 1 | d;
        }
      
        const auto a = std::uniform_int_distribution<uint64_t>{ 0, sum }(engine);
        return { a, sum - a, res };
    }
  
public:
    It(should_pass_random_tests)
    {
        for(int i = 0; i < 100; ++i)
        {
            const auto [a, b, res] = generate_problem();
            const auto msg = [a = a, b = b]
            {
                std::ostringstream res;
                res << "Incorrect result for a = " << a << ", b = " << b;
                return res.str();
            };
          
            Assert::That(add_binary(a, b), Equals(res), msg);
        }
    }
};

解决方案:

format

#include <cstdint>
#include <string>
#include <fmt/core.h>

std::string add_binary(std::uint64_t a, std::uint64_t b) {
  return fmt::format("{:b}", a + b);
}

fmt 是一个三方库

字符串拼接

#include <cstdint>
#include <string>

using namespace std;

string add_binary(uint64_t a, uint64_t b) {
    a += b;
    string output;

    do {
        output = to_string(a % 2) + output;
        a /= 2;
    } while(a > 0);

    return output;
}

连续拼接字符串会产生大量对象,如果利用append 最后 reverce 会快一点。

bitset

#include <cstdint>
#include <string>
#include <bitset>

using namespace std;

std::string add_binary(uint64_t a, uint64_t b) {
  string bi = std::bitset<64>((a + b)).to_string();
  return bi.erase(0, min(bi.find_first_not_of('0'), bi.size()-1));
}

bitset库
C++的 bitset 在 bitset 头文件中,它是一种类似数组的结构,它的每一个元素只能是0或1,每个元素仅用1bit空间。
用字符串构造时,字符串只能包含 ‘0’ 或 ‘1’ ,否则会抛出异常。
构造时,需在<>中表明bitset 的大小(即size)。
在进行有参构造时,若参数的二进制表示比bitset的size小,则在前面用0补充;若比bitsize大,参数为整数时取后面部分,参数为字符串时取前面部分
构造函数:

  bitset<4> bitset1;  //无参构造,长度为4,默认每一位为0

    bitset<8> bitset2(12);  //长度为8,二进制保存,前面用0补充

    string s = "100101";
    bitset<10> bitset3(s);  //长度为10,前面用0补充
    
    char s2[] = "10101";
    bitset<13> bitset4(s2);  //长度为13,前面用0补充

方法:

 bitset<8> foo ("10011011");

    cout << foo.count() << endl;  //5  (count函数用来求bitset中1的位数,foo中共有5个1
    cout << foo.size() << endl;   //8  (size函数用来求bitset的大小,一共有8位

    cout << foo.test(0) << endl;  //true  (test函数用来查下标处的元素是0还是1,并返回false或true,此处foo[0]为1,返回true
    cout << foo.test(2) << endl;  //false  (同理,foo[2]为0,返回false

    cout << foo.any() << endl;  //true  (any函数检查bitset中是否有1
    cout << foo.none() << endl;  //false  (none函数检查bitset中是否没有1
    cout << foo.all() << endl;  //false  (all函数检查bitset中是全部为1


cout << foo.flip(2) << endl;  //10011111  (flip函数传参数时,用于将参数位取反,本行代码将foo下标2处"反转",即0变1,1变0
    cout << foo.flip() << endl;   //01100000  (flip函数不指定参数时,将bitset每一位全部取反

    cout << foo.set() << endl;    //11111111  (set函数不指定参数时,将bitset的每一位全部置为1
    cout << foo.set(3,0) << endl;  //11110111  (set函数指定两位参数时,将第一参数位的元素置为第二参数的值,本行对foo的操作相当于foo[3]=0
    cout << foo.set(3) << endl;    //11111111  (set函数只有一个参数时,将参数下标处置为1

    cout << foo.reset(4) << endl;  //11101111  (reset函数传一个参数时将参数下标处置为0
    cout << foo.reset() << endl;   //00000000  (reset函数不传参数时将bitset的每一位全部置为0


 string s = foo.to_string();  //将bitset转换成string类型
    unsigned long a = foo.to_ulong();  //将bitset转换成unsigned long类型
    unsigned long long b = foo.to_ullong();  //将bitset转换成unsigned long long类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值