从十进制转换的二进制中删除前导零

Remove leading zeroes from Binary converted from Decimal

我正在解决一个问题,我必须将给定的前 N ​​个自然数转换为二进制数。我正在使用 bitset.to_string()。但是,在将数字转换为二进制后,它有一些前导零显然等于给定位集的大小。任务是删除它。我已经使用 std::string:: erase() 做到了,但我认为这不是一个好的方法。如何优化这部分代码?

#include <iostream>
#include <bitset>
#include <string>
int main()
{
    int T;
    std:: cin >> T;
    while(T--) {
    int n;
    std:: cin >> n;
    for(auto i = 1; i <= n; ++i) {
        std::string binary = std::bitset<32>(i).to_string(); //to binary

        //This part here

        int j = 0;
        while(binary[j] == '0') {
            ++j;
        }
        binary.erase(0, j);

        //Till here

        std::cout<<binary<<" ";
    }
    std:: cout << std:: endl;
    }
    return 0;
}

我建议使用 cmath 头文件中的 log2 函数。您可以用它来计算以二进制格式表示整数所需的位数。因此,您不需要使用 while 循环来计算前导零的数量。

代码如下:

#include <iostream>
#include <bitset>
#include <string>
#include <cmath>
int main()
{
    int T;
    std:: cin >> T;
    while(T--) {
    int n;
    std:: cin >> n;
    for(auto i = 1; i <= n; ++i) {
        std::string binary = std::bitset<32>(i).to_string(); //to binary
        int len = log2(i)+1;
        binary.erase(0,32-len);
        std::cout<<binary<<"\n";
    }
    std:: cout << std:: endl;
    }
    return 0;
}

如评论部分john所述,您不一定需要删除前导零的数量。为此,您可以这样做,

std::cout<<binary.substr(32-len,len)<<"\n";

您可以使用 std::string::find_first_not_of() 函数来获取第一个非零字符的位置。然后使用std::string::erase()擦除从字符串开头(索引0)到第一个非零字符的位置。这将避免您当前使用的 while 循环。

示例:

std::string binary = std::bitset<32>(128).to_string(); //"00000000000000000000000010000000"
binary.erase(0, binary.find_first_not_of('0')); //"10000000"
std::cout << binary;