我正在解决一个问题,我必须将给定的前 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/