Arun Suryan
Arun Suryan

Reputation: 1695

Remove leading zeroes from Binary converted from Decimal

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;
}

Upvotes: 6

Views: 7713

Answers (2)

jignatius
jignatius

Reputation: 6474

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;

Upvotes: 9

ChasedByDeath
ChasedByDeath

Reputation: 183

I would suggest to use log2 function from cmath header file. You can count the number of bits you would require to represent the integer in binary format with this. Thus you won't need the while loop used to count the number of leading zeroes.

Here is the code:

#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;
}

As john mentioned in the comment section, you not necessarily need to remove the number of leading zeroes. For that you can do this,

std::cout<<binary.substr(32-len,len)<<"\n";

Upvotes: 2

Related Questions