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?
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.
1 <= T <= 10 ^ 3
0 <= N <= 10 ^ 6
Time Limit: 1 sec
2
10
7
1010
111
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
1100
100001
Can you iterate over all the bits of the given number to find the answer?
The steps are as follows:
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).
O(1), no extra space required.
As we are not using any extra space. Hence, the overall space complexity is O(1).