NINJA’S CALCULATOR
Posted: 23 Feb, 2021
Difficulty: Easy
Ninja and his friends go to the park every day. But now, due to his homework, he wasn’t able to go to the park with his friends. So when he figures out, he notes that a lot of time is consumed in doing maths homework where he has to convert some real number to a binary string. So he is deciding to build a calculator which can convert real numbers to the binary string.
So help our Ninja to write a code for the calculator, which can convert the real numbers into a binary string and save his time to join his friends in the park.
So your task is to write a code that can convert real numbers between ‘0’ and ‘1’into a binary string.
For example, you have given a number “0.750” so you have to convert it in its binary form that is “0.110”
Input Format :
The first line of input contains the ‘T’ number of test cases.
The first line of each test case contains a real number ‘N’ between 0 and 1 (e.g., 0.72) as a double.
Output Format :
For each test case, print the binary representation in form of a string in case the number cannot be represented accurately in binary with at most 32 characters, return string as “ERROR”.
Note :
You don’t have to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 100000
0 <= N < 1
Time Limit: 1 sec
Approach 1
We multiply our number until it is less than 1 or the length is smaller than 32 bits.
- Multiply the number ‘num’ by ‘2’ and check whether the result is greater than ‘1’or not.
- If ‘num > 1’ then
- We append ‘1’ in our ’ ans’ string
- Else
- We append ‘0’ in our ‘ans’ string
Repeat until our number is greater than 0 and in case of string length exceeding
‘32’
Characters return string as “ERROR”.
Approach 2
We instead of multiplying the number by ‘2’ and comparing it to ‘1’, we can compare our number to ‘0.5’, then ’0.25’, and so on.
- We take a double ‘x’ and set its value as ‘ X=0.5’, and compare our number ‘num’ with that ‘x.
- If ‘num > x ’ then
- We append ‘1’ in our ’ ans’ string
- Else
- We append ‘0’ in our ‘ans’ string
- Now we divide our double ‘x’ with ‘2’.
Repeat until our number ‘num’ is greater than 0 and in the case of a string, length exceeds
‘32’
characters return string as “ERROR”.
SIMILAR PROBLEMS
Unit Power Subsets
Posted: 11 Feb, 2022
Difficulty: Hard
Maximum AND Sum of Array
Posted: 7 Apr, 2022
Difficulty: Hard
Detect Odd
Posted: 15 Apr, 2022
Difficulty: Moderate
Ninja And The Clan
Posted: 17 Apr, 2022
Difficulty: Moderate
Check whether K-th bit is set or not
Posted: 20 May, 2022
Difficulty: Easy