Decimal to binary conversion without using arithmetic operators
Find the binary equivalent of the given non-negative number n without using arithmetic operators.
Input : n = 10
Output : 1010
Input : n = 38
Output : 100110
Note that + in below algorithm/program is used for concatenation purpose.
decToBin(n) if n == 0 return "0" Declare bin = "" Declare ch while n > 0 if (n & 1) == 0 ch = '0' else ch = '1' bin = ch + bin n = n >> 1 return bin
Below is the implementation of above approach:
Time complexity: O(num), where num is the number of bits in the binary representation of n.
Auxiliary space: O(num), for using extra space for string bin.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
METHOD 2:Using format()
This code converts a decimal number to binary using the built-in format() function in Python. The function takes two arguments: the first is the number to be converted, and the second is the format specifier ‘b’, which tells the function to convert the number to binary.
1. Take the decimal number as input.
2. Convert the decimal number to binary using the format() function with the format specifier ‘b’.
3. Store the result in a variable.
4. Print the variable.
The binary representation of 38 is: 100110 The binary representation of 10 is: 1010
Time complexity: O(log n), where n is the decimal number, because the number of iterations required in the format() function depends on the number of bits required to represent the number in binary, which is log2(n).
Space complexity: O(log n), because the space required to store the binary representation of the number in the variable also depends on the number of bits required to represent the number in binary, which is log2(n).
Please Login to comment...