从十进制转换为二进制后,如何去掉前导零

6

我正在解决一个问题,需要将前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;
}

你可以计算你的数字的log2以确定位数。 - MH Alikhani
2
不要从字符串中删除零,只是不要打印它们,例如 std::cout << binary.c_str() + j << " "; - john
2个回答

9
你可以使用 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;

2
我建议使用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";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接