博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode166. Fraction to Recurring Decimal(思路及python解法)
阅读量:2241 次
发布时间:2019-05-09

本文共 1217 字,大约阅读时间需要 4 分钟。

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

Example 1:

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

Example 2:

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

Example 3:

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

 看了discuss才有思路。鉴于python除法问题多多(负数除法),所以先给转为正数相除,再判断符号。

result记录读数结果,reminders记录每次余数(也就是笔算除法时候最上面一排数,如果有重复则会出现循环小数)。

如果能除尽(remainder=0),也就是说没有循环小数,则会以(0)结束。

如果存在循环小数,那么则会出现相同的remainder,第二次出现的remainder就是循环起始的数字,此时跳出while循环,加上括号。

class Solution:    def fractionToDecimal(self, numerator: int, denominator: int) -> str:        res,remainder = divmod(abs(numerator), abs(denominator))        sym= '-' if numerator*denominator<0 else ''        result=[sym,str(res),'.']        reminders=[]                while remainder not in reminders:            reminders.append(remainder)            res,remainder=divmod(remainder*10, abs(denominator))            result.append(str(res))        index=reminders.index(remainder)        result.insert(index+3,'(')        result.append(')')                return ''.join(result).replace('(0)','').rstrip('.')

 

转载地址:http://djrbb.baihongyu.com/

你可能感兴趣的文章
Oracle数据库面试题
查看>>
java面试中的智力题
查看>>
本地如何连接hbase数据库
查看>>
Maven出错-Missing artifact org.apache.openejb:openejb-core:jar:4.1.0-SNAPSHOT:test
查看>>
dubbo配置文件xml校验报错
查看>>
eclipse生成export生成jar详解
查看>>
oracle 模糊查询忽略大小写
查看>>
Java项目导出可运行的jar文件
查看>>
Java文件夹操作,判断多级路径是否存在,不存在就创建(包括windows和linux下的路径字符分析),兼容Windows和Linux
查看>>
JAVA读取PROPERTIES配置文件
查看>>
Linux中执行shell脚本的4种方法总结
查看>>
BufferedInputStream(缓冲输入流)详解
查看>>
修改linux文件权限命令:chmod
查看>>
Linux vi/vim编辑器常用命令与用法总结
查看>>
如何使用Git Bash Here,将本地项目传到github上
查看>>
eclipse git控件操作 回退到历史提交 重置 删除(撤销)历史的某次提交
查看>>
Oracle | 给表和字段添加注释
查看>>
java比较日期大小及日期与字符串的转换【SimpleDateFormat操作实例】
查看>>
Oracle新表使用序列(sequence)作为插入值,初始值不是第一个,oraclesequence
查看>>
java中System.exit()方法
查看>>