Bitwise Operators: Print the binary representation of a given number.

Problem Statement:

You are given an integer n, you need to print the binary representation of the number,

Example:

Input n = 2

Output: 00000000000000000000000000000010

Solution 1:

Solution is to check each bit position of the number from left to right (MSB to LSB).

For each index, use bitwise AND operation with a mask created by left-shifting 1 to that position.

If the result is non zero, it means that bit is set to 1 in the number.

Append 1 to the result, else append 0.

Code Solution

#include<iostream>
using namespace std;

string solution(int n) 
{

    string ans = "";
    
    for (int i=31; i>=0; i--) 
    {
        
        // check if ith bit is set
        if (n&(1<<i))
            ans += '1';
        else 
            ans += '0';
    }
    
    return ans;
}

int main() {
    int n = 2;
    cout << solution(n);

    return 0;
}

Output

00000000000000000000000000000010

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *