程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

(practice Python every day) fraction to decimal

編輯:Python

Fractions to decimals

Given two integers , Molecules representing fractions respectively  numerator  Denominator  denominator, With   Returns a decimal as a string  .

If the decimal part is a circular decimal , The loop is enclosed in brackets .

If there are multiple answers , Just go back   Any one  .

For all given inputs , Guarantee   The length of the answer string is less than  104 .

Example 1:

 Input :numerator = 1, denominator = 2
 Output :"0.5"

Example 2:

 Input :numerator = 2, denominator = 1
 Output :"2"

Example 3:

 Input :numerator = 2, denominator = 3
 Output :"0.(6)"

Example 4:

 Input :numerator = 4, denominator = 333
 Output :"0.(012)"

Example 5:

 Input :numerator = 1, denominator = 5
 Output :"0.2"

Tips :

  • -2^31 <= numerator, denominator <= 2^31 - 1
  • denominator != 0
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
if numerator < 0 and denominator < 0:
numerator, denominator = -numerator, -denominator
u = (numerator < 0) ^ (denominator < 0)
numerator = abs(numerator)
denominator = abs(denominator)
numerator = numerator % denominator
if numerator == 0:
return str(numerator // denominator)
s = str(abs(numerator) // denominator) + "."
q = {}
l = []
while numerator < denominator:
numerator = numerator * 10
l.append(numerator)
q[numerator] = numerator // denominator
numerator = numerator % denominator * 10
while numerator not in q and numerator != 0:
l.append(numerator)
q[numerator] = numerator // denominator
numerator = numerator % denominator
numerator = numerator * 10
for i in range(0, len(l)):
if numerator == l[i]:
s = s + "("
s = s + str(q[l[i]])
if "(" in s:
s = s + ")"
if u:
s = "-" + s
return s

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved