VOOZH about

URL: https://www.geeksforgeeks.org/dsa/binary-representation-of-a-given-number/

⇱ Binary representation of a given number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Binary representation of a given number

Last Updated : 17 Mar, 2025

Given an integer n, the task is to print the binary representation of the number. 

Note: The given number will be maximum of 32 bits, so append 0's to the left if the result string is smaller than 30 length.

Examples:

Input: n = 2
Output: 00000000000000000000000000000010

Input: n = 0
Output: 00000000000000000000000000000000

Approach - Using Bit Manipulation - O(1) time and O(1) space

The idea is to check each bit position of the number from left to right (most significant bit to least significant bit). For each bit position, we use the bitwise AND operation with a mask created by left-shifting 1 to that position (1<<i). If the result is non-zero, it means that bit is set to 1 in the original number, so we append '1' to our answer string; otherwise, we append '0'.


Output
00000000000000000000000000000010

Approach - Using Modulus and Division Operator - O(1) time and O(1) space

The idea is to build a 32-bit binary representation by examining each bit of the number from right to left. We start by creating a string of 32 zeros, then iterate through all 32 bit positions. For each position, we check if the current rightmost bit is set (using n%2), and if so, we place a '1' at the appropriate position in our string. After checking each bit, we right-shift the number (using integer division by 2) to examine the next bit in the subsequent iteration.

The expression n%2 (n modulo 2) reveals the rightmost bit because any binary number ends with either 0 or 1. If the number is odd, it ends with 1 and n%2 equals 1; if it's even, it ends with 0 and n%2 equals 0. Meanwhile, the integer division n/2 effectively performs a right shift operation in binary. When we divide by 2, we're removing the rightmost bit and shifting all other bits one position to the right. For example, 10 (binary 1010) divided by 2 gives 5 (binary 101), effectively shifting all bits right by one position.


Output
00000000000000000000000000000010
Comment
Article Tags: