![]() |
VOOZH | about |
Given a non negative number n, the task is to convert the given number into an equivalent binary representation.
Examples:
Input: n = 12
Output: "1100"
Explanation: the binary representation of 12 is "1100", since 12 = 1×23 + 1×22 + 0×21+ 0×20 = 12Input: n = 33
Output: "100001"
Explanation: the binary representation of 33 is "100001", since 1×25 + 0×24 + 0×23 + 0×22 + 0×21 + 1×20 = 33
Table of Content
To convert a decimal number to binary, repeatedly divide it by 2 and record the remainders. Reading these remainders in reverse gives the binary representation.
1100
The idea is same as the previous approach, but we will use recursion to generate the binary equivalent number.
1100
Using bitwise operators, we can extract binary digits by checking the least significant bit (
n & 1) and then right-shifting the number (n >> 1) to process the next bit.
This method is faster than arithmetic division and modulo, as bitwise operations are more efficient at the hardware level.
1100
The main idea is to leverage built-in functions provided by programming languages to directly convert a decimal number to its binary form. These functions abstract away the underlying logic and return the binary representation as a string, making the process quick, concise, and error-free.
1100