给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 "ERROR"
。
样例
n = "3.72"
, 返回 "ERROR"
.
n = "3.5"
, 返回 "11.1"
思路:
将n转化为整数部分与小数部分,分别转化成字符串形式再相加,用到
split() 字符串分割函数
bin() 整数转二进制字符串函数 2 - ‘0b10‘
class Solution: """ @param: n: Given a decimal number that is passed in as a string @return: A string """ def binaryRepresentation(self, n): # write your code here Integer,decimal = n.split(‘.‘) Integer = int(Integer) decimal = float(‘0.‘+decimal) Integer_str = str(bin(int(Integer)))[2:] if decimal == 0: return Integer_str decimal_list = [] for i in range(32): decimal *= 2 decimal_list.append(int(decimal)) decimal -= int(decimal) if decimal == 0: break decimal_str = "." for i in decimal_list: decimal_str += str(i) if len(decimal_str) > 32: return "ERROR" else: return Integer_str + decimal_str
九章参考:
from decimal import * class Solution: #@param n: Given a decimal number that is passed in as a string #@return: A string def binaryRepresentation(self, num): (a, b) = num.split(‘.‘) a = ‘{:b}‘.format(int(a)) b = self.frac_to_binary(b) if b is None: return ‘ERROR‘ elif b == ‘‘: return a else: return a + ‘.‘ + b def frac_to_binary(self, num): if int(num) == 0: return ‘‘ if int(num) % 10 != 5: return None res = ‘‘ num = Decimal(‘0.‘ + str(num)) while num: num *= 2 if num >= 1: res += ‘1‘ num -= 1 else: res += ‘0‘ num = num.normalize() if num and str(num)[-1] != ‘5‘: return None return res
.format() 格式化字符串函数