I am solving a problem where I have to convert given first N natural numbers to binary numbers. I am using bitset
and .to_string()
. But, after the number is converted to binary it has some leading zeroes obviously as equal to the size of the given bitset. The task is to remove that. I have done that using std::string:: erase()
But I think it's not a good approach to do so. How can I optimize this part of the code?
#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;
}
You could make use of the std::string::find_first_not_of()
function to get the position of the first character that isn't a zero. Then use std::string::erase()
to erase from the beginning of the string (index 0) to the position of the first non-zero character. This will avoid the while loop you're currently using.
Example:
std::string binary = std::bitset<32>(128).to_string(); //"00000000000000000000000010000000"
binary.erase(0, binary.find_first_not_of('0')); //"10000000"
std::cout << binary;