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

标签 c++ string loops binary 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;
}

最佳答案

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

关于c++ - 从十进制转换的二进制中删除前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61182586/

相关文章:

c++ - 为什么不能使用Sphere缩放字形?

c++ - 创建返回导出 11 的大型一维矩阵

java - Java 中的内联字符串替换?

jquery - 使用 jQuery 遍历 HTML 复选框

mysql - 需要通过更改参数来循环 MySql 查询

C++:运算符重载:类内和类外。预自增运算符的歧义

c++ - 如何在同一文件 C++ 中使用重载 []

在没有任何标准库的情况下比较不同长度的字符串

c# - `\` 的字符串替换没有达到我的预期。是什么赋予了?

function - 在 Julia 的 for 循环中索引函数的名称