The Wayback Machine - https://web.archive.org/web/20241129152006/https://www.geeksforgeeks.org/binary-representation-of-a-given-number/
Open In App

Binary representation of a given number

Last Updated : 17 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Write a program to print a Binary representation of a given number. 

Source: Microsoft Interview Set-3 

Method 1: Iterative Method:

For any number, we can check whether its ‘i’th bit is 0(OFF) or 1(ON) by bitwise AND it with “2^i” (2 raise to i). 

1) Let us take number 'NUM' and we want to check whether it's 0th bit is ON or OFF    
bit = 2 ^ 0 (0th bit)
if NUM & bit >= 1 means 0th bit is ON else 0th bit is OFF
2) Similarly if we want to check whether 5th bit is ON or OFF
bit = 2 ^ 5 (5th bit)
if NUM & bit >= 1 means its 5th bit is ON else 5th bit is OFF.

Let us take unsigned integers (32 bits), which consists of 0-31 bits. To print the binary representation of an unsigned integer, start from 31th bit, and check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.

Below is the implementation of the above approach:

C++
// C++ Program for the binary
// representation of a given number
#include <bits/stdc++.h>
using namespace std;

void bin(long n)
{
    long i;
    cout << "0";
    for (i = 1 << 31; i > 0; i = i / 2) {
        if ((n & i) != 0) {
            cout << "1";
        }
        else {
            cout << "0";
        }
    }
}

// Driver Code
int main(void)
{
    bin(7);
    cout << endl;
    bin(4);
}
C
#include <stdio.h>

void bin(long n)
{
    long i;
    printf("0");
    for (i = 1 << 31; i > 0; i = i / 2) {
        if ((n & i) != 0) {
            printf("1");
        }
        else {
            printf("0");
        }
    }
}

int main(void)
{
    bin(7);
    printf("\n");
    bin(4);
    
    return 0;
}
Java
public class GFG {
    static void bin(long n)
    {
        long i;
        System.out.print("0");
        for (i = 1 << 31; i > 0; i = i / 2) {
            if ((n & i) != 0) {
                System.out.print("1");
            }
            else {
                System.out.print("0");
            }
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        bin(7);
        System.out.println();
        bin(4);
    }
}

// This code is contributed by divyesh072019.
Python
def bin_representation(n):
    binary_str = "0"
    for i in range(31, -1, -1):
        if n & (1 << i):
            binary_str += "1"
        else:
            binary_str += "0"
    return binary_str

def main():
    print(bin_representation(7))
    print(bin_representation(4))

if __name__ == "__main__":
    main()
C#
using System;

public class GFG {
    static void bin(long n)
    {
        long i;
        Console.Write("0");
        for (i = 1 << 31; i > 0; i = i / 2) {
            if ((n & i) != 0) {
                Console.Write("1");
            }
            else {
                Console.Write("0");
            }
        }
    }
    // Driver code
    static public void Main()
    {
        bin(7);
        Console.WriteLine();
        bin(4);
    }
}
// This code is contributed by avanitrachhadiya2155
JavaScript
function bin(n) {
    let result = "";
    for (let i = 1 << 30; i >= 1; i = i / 2) {
        if ((n & i) !== 0) {
            result += "1";
        } else {
            result += "0";
        }
    }
    return result;
}

function main() {
    console.log("0" + bin(7));
    console.log("0" + bin(4));
}

main();

Output
0
0

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 2: Recursive Approach:

Following is recursive method to print binary representation of ‘NUM’. 

step 1) if NUM > 1
a) push NUM on stack
b) recursively call function with 'NUM / 2'
step 2)
a) pop NUM from stack, divide it by 2 and print it's remainder.

Below is the implementation of the above approach:

C++
// C++ Program for the binary
// representation of a given number
#include <bits/stdc++.h>
using namespace std;

void bin(unsigned n)
{
    /* step 1 */
    if (n > 1)
        bin(n / 2);

    /* step 2 */
    cout << n % 2;
}

// Driver Code
int main(void)
{
    bin(7);
    cout << endl;
    bin(4);
}
C
// C Program for the binary
// representation of a given number
void bin(unsigned n)
{
    /* step 1 */
    if (n > 1)
        bin(n / 2);

    /* step 2 */
    printf("%d", n % 2);
}

// Driver Code
int main(void)
{
    bin(7);
    printf("\n");
    bin(4);
}
Java
// Java Program for the binary
// representation of a given number
class GFG {
    static void bin(int n)
    {
        /* step 1 */
        if (n > 1)
            bin(n / 2);

        /* step 2 */
        System.out.print(n % 2);
    }

    // Driver code
    public static void main(String[] args)
    {
        bin(7);
        System.out.println();
        bin(4);
    }
}

// This code is contributed
// by ChitraNayal
Python
# Python3 Program for the binary
# representation of a given number


def bin(n):

    if n > 1:
        bin(n//2)

    print(n % 2, end="")


# Driver Code
if __name__ == "__main__":

    bin(7)
    print()
    bin(4)

# This code is contributed by ANKITRAI1
C#
// C# Program for the binary
// representation of a given number
using System;

class GFG {

    static void bin(int n)
    {

        // step 1
        if (n > 1)
            bin(n / 2);

        // step 2
        Console.Write(n % 2);
    }

    // Driver code
    static public void Main()
    {
        bin(7);
        Console.WriteLine();
        bin(4);
    }
}

// This code is contributed ajit
JavaScript
<script>

// Javascript program for the binary
// representation of a given number
function bin(n)
{
    
    // Step 1
    if (n > 1)
        bin(parseInt(n / 2, 10));

    // Step 2
    document.write(n % 2);
}

// Driver code
bin(7);
document.write("</br>");
bin(4);

// This code is contributed by divyeshrabadiya07

</script>
PHP
<?php
// PHP Program for the binary 
// representation of a given number
function bin($n)
{
    /* step 1 */
    if ($n > 1)
        bin($n/2);

    /* step 2 */
    echo ($n % 2);
}

// Driver code
bin(7);
echo ("\n");
bin(4);

// This code is contributed 
// by Shivi_Aggarwal
?>

Output
111
100

Time Complexity: O(log N)
Auxiliary Space: O(log N)

Method 3: Recursive using bitwise operator 

Steps to convert decimal number to its binary representation are given below: 

  1. Check n > 0
  2. Right shift the number by 1 bit and recursive function call
  3. Print the bits of number

Below is the implementation of the above approach:

C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;

// Function to convert decimal
// to binary number
void bin(unsigned n)
{
    if (n > 1)
        bin(n >> 1);

    printf("%d", n & 1);
}

// Driver code
int main(void)
{
    bin(131);
    printf("\n");
    bin(3);
    return 0;
}
Java
// Java implementation of the approach

class GFG {

    // Function to convert decimal
    // to binary number
    static void bin(Integer n)
    {
        if (n > 1)
            bin(n >> 1);

        System.out.printf("%d", n & 1);
    }

    // Driver code
    public static void main(String[] args)
    {
        bin(131);
        System.out.printf("\n");
        bin(3);
    }
}
/*This code is contributed by PrinciRaj1992*/
Python
# Python 3 implementation of above approach

# Function to convert decimal to
# binary number


def bin(n):

    if (n > 1):
        bin(n >> 1)
    print(n & 1, end="")


# Driver code
bin(131)
print()
bin(3)

# This code is contributed by PrinciRaj1992
C#
// C# implementation of above approach
using System;

public class GFG {

    // Function to convert decimal
    // to binary number
    static void bin(int n)
    {
        if (n > 1)
            bin(n >> 1);

        Console.Write(n & 1);
    }

    // Driver code
    public static void Main()
    {
        bin(131);
        Console.WriteLine();
        bin(3);
    }
}
/*This code is contributed by PrinciRaj1992*/
JavaScript
<script>
// JavaScript implementation of the approach

// Function to convert decimal
// to binary number
function bin(n)
{
    if (n > 1)
        bin(n >> 1);

    document.write(n & 1);
}

// Driver code

    bin(131);
    document.write("<br>");
    bin(3);


// This code is contributed by Surbhi Tyagi.

</script>
PHP
<?php
// PHP implementation of the approach

// Function to convert decimal
// to binary number
function bin($n)
{
    if ($n > 1)
    bin($n>>1);
    
    echo ($n & 1);
}

// Driver code
bin(131);
echo "\n";
bin(3);

// This code is contributed
// by Akanksha Rai

Output
10000011
11

Time Complexity: O(log N)
Auxiliary Space: O(log N)

This article is compiled by Narendra Kangralkar. 



Previous Article
Next Article

Similar Reads

Number of leading zeros in binary representation of a given number
Given a positive integer N, the task is to find the number of leading zeros in its binary representation.A leading zero is any 0 digit that comes before the first nonzero digit in a number's binary form. Examples: Input : N = 16Output : 27Explanation: As Binary(16) = (00000000000000000000000000010000) Input : N = 33Output : 26Explanation: As Binary
10 min read
Find the occurrence of the given binary pattern in the binary representation of the array elements
Given an array arr[] of N positive integers and a string patt which consists of characters from the set {0, 1}, the task is to find the count occurrence of patt in the binary representation of every integer from the given array. Examples: Input: arr[] = {5, 106, 7, 8}, patt = "10" Output: 1 3 0 1 binary(5) = 101 -> occurrence(10) = 1 binary(106)
9 min read
Check if given number contains only “01” and “10” as substring in its binary representation
Given a number N, the task is to check if the binary representation of the number N has only "01" and "10" as a substring or not. If found to be true, then print "Yes". Otherwise, print "No".Examples: Input: N = 5 Output: Yes Explanation: (5)10 is (101)2 which contains only "01" and "10" as substring.Input: N = 11 Output: No Explanation: (11)10 is
6 min read
Count trailing zeroes present in binary representation of a given number using XOR
Given an integer N, the task is to find the number of trailing zeroes in the binary representation of the given number. Examples: Input: N = 12Output: 2Explanation:The binary representation of the number 13 is "1100".Therefore, there are two trailing zeros in the 12. Input: N = -56Output: 3Explanation:The binary representation of the number -56 is
4 min read
Check if binary representation of a given number and its complement are anagram
Given a positive number you need to check whether it's complement and the number are anagrams or not.Examples: Input : a = 4294967295 Output : Yes Binary representation of 'a' and it's complement are anagrams of each other Input : a = 4 Output : No Simple Approach: In this approach calculation of the complement of the number is allowed.1. Find bina
9 min read
Check if the binary representation of a number has equal number of 0s and 1s in blocks
Given an integer N, the task is to check if its equivalent binary number has an equal frequency of consecutive blocks of 0 and 1. Note that 0 and a number with all 1s are not considered to have a number of blocks of 0s and 1s. Examples: Input: N = 5 Output: Yes Equivalent binary number of 5 is 101. The first block is of 1 with length 1, the second
10 min read
Count number of trailing zeros in Binary representation of a number using Bitset
Given a number. The task is to count the number of Trailing Zero in Binary representation of a number using bitset. Examples: Input : N = 16Output : 4Binary representation of N is 10000. Therefore,number of zeroes at the end is 4.Input : N = 8Output : 3Recommended: Please try your approach on {IDE} first, before moving on to the solution.Approach:
5 min read
Binary representation of next greater number with same number of 1's and 0's
Given a binary input that represents binary representation of positive number n, find binary representation of smallest number greater than n with same number of 1's and 0's as in binary representation of n. If no such number can be formed, print "no greater number".The binary input may be and may not fit even in unsigned long long int. Examples: I
12 min read
Decimal representation of given binary string is divisible by 20 or not
The problem is to check whether the decimal representation of the given binary number is divisible by 20 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or the minimum numbers of multiplication and division operations. No leadings 0’s are there in the input. Ex
14 min read
Construct Binary Tree from given Parent Array representation | Iterative Approach
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation
12 min read
Count numbers from a given range having same first and last digits in their binary representation
Given two integers L and R, the task is to find the count of numbers in the range [L, R] whose first and last digit in the binary representation are the same. Examples: Input: L = 1, R = 5Output: 3Explanation:(1)10 = (1)2(2)10 = (10)2(3)10 = (11)2(4)10 = (100)2(5)10 = (101)2Therefore, 1, 3, 5 has the same first and last digits in their binary repre
4 min read
Decimal representation of given binary string is divisible by 10 or not
The problem is to check whether the decimal representation of the given binary number is divisible by 10 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or minimum number of multiplication and division operations. No leading 0’s are there in the input.Examples:
14 min read
Construct Binary Tree from given Parent Array representation
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of given Binary Tree from this given representation
15+ min read
Decimal representation of given binary string is divisible by 5 or not
The problem is to check whether the decimal representation of the given binary number is divisible by 5 or not. Take care, the number could be very large and may not fit even in long long int. The approach should be such that there are zero or minimum number of multiplication and division operations. No leading 0's are there in the input. Examples:
12 min read
Length of longest consecutive zeroes in the binary representation of a number.
We have a number N. Determine the length of the longest consecutive 0's in its binary representation. Examples: Input : N = 14 Output : 1 Binary representation of 14 is 1110. There is only one 0 in the binary representation. Input : N = 9 Output : 2 A simple approach is to traverse through all bits and keep track of the maximum number of consecutiv
4 min read
Sum of decimal equivalent of all possible pairs of Binary representation of a Number
Given a number N. The task is to find the sum of the decimal equivalent of all the pairs formed from the binary representation of the given number. Examples: Input: N = 4 Output: 4 Binary equivalent of 4 is 100. All possible pairs are 10, 10, 00 and their decimal equivalent are 2, 2, 0 respectively. So, 2 + 2+ 0 = 4 Input: N = 11 Output: 13 All pos
5 min read
Next greater number than N with exactly one bit different in binary representation of N
Given a number N. The task is to find the smallest number which is greater than N and has only one bit different in the binary representation of N. Note: Here N can be very large 10^9 < N < 10^15.Examples: Input : N = 11 Output : The next number is 15 The binary representation of 11 is 1011 So the smallest number greater than 11 with one bit
7 min read
Number of mismatching bits in the binary representation of two integers
Given two integers(less than 2^31) A and B. The task is to find the number of bits that are different in their binary representation. Examples: Input : A = 12, B = 15 Output : Number of different bits : 2 Explanation: The binary representation of 12 is 1100 and 15 is 1111. So, the number of different bits are 2. Input : A = 3, B = 16 Output : Numbe
8 min read
Find consecutive 1s of length >= n in binary representation of a number
Given two integers x and n, the task is to search for the first consecutive stream of 1s (in the x's 32-bit binary representation) which is greater than or equal to n in length and return its position. If no such string exists then return -1.Examples: Input: x = 35, n = 2 Output: 31 Binary representation of 35 is 00000000000000000000000000100011 an
10 min read
Maximum number of consecutive 1's in binary representation of all the array elements
Given an array arr[] of N elements, the task is to find the maximum number of consecutive 1's in the binary representation of an element among all the elements of the given array. Examples: Input: arr[] = {1, 2, 3, 4} Output: 2 Binary(1) = 01 Binary(2) = 10 Binary(3) = 11 Binary(4) = 100 Input: arr[] = {10, 15, 37, 89} Output: 4 Approach: An approa
6 min read
Find the number obtained after concatenation of binary representation of M and N
Given two integers M and N the task is to find the number formed by concatenating the binary equivalents of M and N i.e. M + N. Examples: Input: M = 4, N = 5 Output: 37 Binary equivalent of 4 is 100 and for 5 it is 101 after concatenation, the resultant binary number formed is 100101 whose decimal equivalent is 37. Input: M = 3, N = 4 Output: 28 Ap
11 min read
Smallest multiple of N with exactly N digits in its Binary number representation
Given a positive integer N, the task is to find the smallest multiple of N with exactly N digits in its binary number representation.Example: Input: N = 3 Output: 6 Explanation: 6 is the smallest multiple of 3 and has length also 3(110) in binary.Input: N = 5 Output: 20 Explanation: 6 is the smallest multiple of 5 and has length also 5(10100) in bi
3 min read
Find the maximum between N and the number formed by reversing 32-bit binary representation of N
Given a positive 32-bit integer N, the task is to find the maximum between the value of N and the number obtained by decimal representation of reversal of binary representation of N in a 32-bit integer. Examples: Input: N = 6Output: 1610612736Explanation: Binary representation of 6 in a 32-bit integer is 00000000000000000000000000000110 i.e., (0000
6 min read
Prime Number of Set Bits in Binary Representation | Set 1
Given two integers ‘L’ and ‘R’, write a program to find the total numbers that are having prime number of set bits in their binary representation in the range [L, R]. Examples: Input : l = 6, r = 10Output : 4Explanation :6 -> 110 (2 set bits, 2 is prime)7 -> 111 (3 set bits, 3 is prime)9 -> 1001 (2 set bits, 2 is prime)10 -> 1010 (2 set
13 min read
Check if actual binary representation of a number is palindrome
Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0’s are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Input : 10 Output : No (10)10 = (1010)2Recommended Pr
6 min read
Check if binary representation of a number is palindrome
Given an integer 'x', write a C function that returns true if binary representation of x is palindrome else return false.For example a numbers with binary representation as 10..01 is palindrome and number with binary representation as 10..00 is not palindrome.The idea is similar to checking a string is palindrome or not. We start from leftmost and
15 min read
Binary representation of next number
Given a binary input that represents binary representation of positive number n, find a binary representation of n+1.The binary input may be and may not fit even in unsigned long long int. Examples: Input: 10011Output: 10100Explanation:Here n = (19)10 = (10011)2next greater integer = (20)10 = (10100)2 Input: 111011101001111111Output: 11101110101000
9 min read
Prime Number of Set Bits in Binary Representation | Set 2
Given two integers 'L' and 'R', we need to write a program that finds the count of numbers having the prime number of set bits in their binary representation in the range [L, R]. Examples: Input : 6 10 Output : 4 6 -> 110 (2 set bits, 2 is prime) 7 -> 111 (3 set bits, 3 is prime) 9 -> 1001 (2 set bits , 2 is prime) 10->1010 (2 set bits
9 min read
Find the n-th number whose binary representation is a palindrome
Find the nth number whose binary representation is a palindrome. Do not consider the leading zeros, while considering the binary representation. Consider the 1st number whose binary representation is a palindrome as 1, instead of 0  Examples:  Input : 1Output : 11st Number whose binary representation is palindrome is 1 (1)Input : 9Output : 279th Nu
15+ min read
Binary representation of previous number
Given a binary input that represents binary representation of positive number n, find binary representation of n-1. It may be assumed that input binary number is greater than 0.The binary input may or may not fit even in unsigned long long int. Examples: Input : 10110Output : 10101Here n = (22)10 = (10110)2Previous number = (21)10 = (10101)2Input :
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg