1. 程式人生 > >lintcode_180.二進制表示

lintcode_180.二進制表示

返回 solution ati 部分 none class lintcode split ret

給定一個數將其轉換為二進制(均用字符串表示),如果這個數的小數部分不能在 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() 格式化字符串函數

lintcode_180.二進制表示