Binary Confusion

Easy
0/40
Average time to solve is 10m
profile
Contributed by
16 upvotes

Problem statement

In the event of confusion, Ninja and his friends were asked to solve an easy problem given by their teacher. However, even after taking several hours, they could not solve the problem.

A value of decimal number ‘N’ is given to them, and they are asked to convert it into its binary equivalent and return it as the answer. Since they are stuck for a while, they ask you to solve the problem. Can you help solve this problem?

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases. The test cases follow.

The first line of each test case contains a single integer ‘N’, given to Ninja and his friends.
Output Format:
For each test case, print the binary equivalent of the given number.

Print the output of each test case in a separate line.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10 ^ 3
0 <= N <= 10 ^ 6


Time Limit: 1 sec
Sample Input 1:
2
10
7
Sample Output 1:
1010
111
Explanation for Sample Input 1:
In the first test case, the value of ‘N’ is 10, so:

1) Remainder when ten is divided by 2 is zero.
2) Divide ten by 2. New number is 10/2 = 5. 
3) Remainder when five is divided by 2 is 1
4) Divide five by 2. New number is 5/2 = 2. 
5) Remainder when two is divided by 2 is zero.
6) Divide two by 2. New number is 2/2 = 1. 
7) Remainder when one is divided by two is 1.
8) Divide 1 by 2. New number is 1/2 = 0. 

 Since the number becomes = 0, break out of the loop. So the final answer is the reverse of all the remainders obtained which is 1010.

 In the second test case, ‘N’ is 7, and we apply similar steps as given above. 
 The final answer comes out to be 111.

Sample Input 2:

2
12
33
Sample Output 2:
1100   
100001
Hint

Can you iterate over all the bits of the given number to find the answer?

Approaches (1)
Brute Force

The steps are as follows:

  • First declare an empty string, say ‘binary’.
  • Now iterate till ‘n’ is greater than 0 with the help of iterator pointer ‘i’.
  • Check if n is even. If yes then push back “0” in the string ‘binary’.
  • If no then push back “1” in the string ‘binary’.
  • Now make n = n / 2.
  • Return ‘binary’ to the function.
Time Complexity

O(log N), where N is the decimal number given.

 

We are traversing the loop till N is greater than 0,  and on each iteration, N gets divided by 2, making the time complexity logarithmic. Since the number gets divided by two each time, the base of the logarithmic time complexity will be 2.Hence; the overall time complexity is O(log N).

Space Complexity

O(1), no extra space required.

 

As we are not using any extra space. Hence, the overall space complexity is O(1).


 

Code Solution
(100% EXP penalty)
Binary Confusion
Full screen
Console