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

Aru*_*yan 5 c++ string binary loops bitset

我正在解决一个问题,我必须将给定的前 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;
}
Run Code Online (Sandbox Code Playgroud)

jig*_*ius 6

您可以使用该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;
Run Code Online (Sandbox Code Playgroud)