我正在解决一个问题,我必须把给定的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;
}发布于 2020-04-13 07:02:41
您可以使用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;发布于 2020-04-13 06:39:36
我建议使用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";https://stackoverflow.com/questions/61182586
复制相似问题