我正在解决一个问题,需要将前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::cout << binary.c_str() + j << " ";
- john