leetcode-面试题 05.02. Binary Number to String LCCI
Description
Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print “ERROR”.
Example1:
Input: 0.625Output: "0.101"
Example2:
Input: 0.1
Output: “ERROR”
Note: 0.1 cannot be represented accurately in binary.
Note:
This two charaters "0." should be counted into 32 characters.
The number of decimal places for num is at most 6 digits
Solution
How to represent a decimal into binary? Like how we represent integers into binary, first choose the maximum power of 2, put 1
to that digit, minus the power from num
, then iterate until num=0num=0num=0
It’s even easier to implement when it comes to decimal. Because we get the maximum power of 2 first (0.5)
Time complexity: o(n)o(n)o(n)
Space complexity: o(1)o(1)o(1)
Code
class Solution:def printBin(self, num: float) -> str:res = []n = 1while len(res) <= 30 and num != 0:cur_binary_num = 1 / (2 ** n)if num >= cur_binary_num:res.append('1')num -= cur_binary_numelse:res.append('0')n += 1return '0.{}'.format(''.join(res)) if num == 0 else 'ERROR'