【LeetCode】166. Fraction to Recurring Decimal 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/fraction-to-recurring-decimal/description/

题目描述:

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 = 2
Output: "0.5"

Example 2:

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

Example 3:

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

题目大意

计算两个整数的除法,结果可能是小数。如果是循环小数,那么就把循环的部分用括号括起来。

解题方法

复习一下整数除法,用长除式的时候,不断地得到当前除法的商和余数,然后给余数部分补零继续做除法。当我们遇到了一个余数,而且这个余数在前面已经出现过了,那么就是出现了循环了。

所以,我们需要一个dict来保存出现过的余数,以及得出这个余数时候,结果出现的位置。所以再次得到这个余数的时候,就查出来了上次出现了的位置,中间这一段就是循环小数部分。

另外特别注意的是,这个题目支持负数除法,所以最好的方法全部转化为正整数的除法,先判断结果的符号,然后把结果变成正数。

代码如下:

class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
d = dict()
div, mod = self.divmod(numerator, denominator)
if mod == 0:
return str(div)
ans = "-" if ((numerator > 0) ^ (denominator > 0)) else ""
div, mod, denominator = abs(div), abs(mod), abs(denominator)
ans += str(div) + "."
d[mod] = len(ans)
while mod:
mod *= 10
div, mod = self.divmod(mod, denominator)
ans += str(div)
if mod in d:
index = d[mod]
ans = ans[:index] + "(" + ans[index:] + ")"
break
else:
d[mod] = len(ans)
return ans def divmod(self, a, b):
q = int(a / b) # I'm using 3.x
r = a - b * q
return (q, r)

上面的代码自定义了divmod是因为python的divmod是向下取整,这样的话对于负数不友好。既然按照上面的思路先转化为正数再算,就可以使用原生的divmod。代码如下:

class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0: return "0"
d = dict()
ans = "-" if ((numerator > 0) ^ (denominator > 0)) else ""
numerator, denominator = abs(numerator), abs(denominator)
div, mod = divmod(numerator, denominator)
if mod == 0: return ans + str(div)
ans += str(div) + "."
d[mod] = len(ans)
while mod:
mod *= 10
div, mod = divmod(mod, denominator)
ans += str(div)
if mod in d:
index = d[mod]
ans = ans[:index] + "(" + ans[index:] + ")"
break
else:
d[mod] = len(ans)
return ans

日期

2018 年 9 月 8 日 ———— 美好的周末,从刷题开始

【LeetCode】166. Fraction to Recurring Decimal 解题报告(Python)的更多相关文章

  1. Leetcode 166. Fraction to Recurring Decimal 弗洛伊德判环

    分数转小数,要求输出循环小数 如2 3 输出0.(6) 弗洛伊德判环的原理是在一个圈里,如果一个人的速度是另一个人的两倍,那个人就能追上另一个人.代码中one就是速度1的人,而two就是速度为2的人. ...

  2. Java for LeetCode 166 Fraction to Recurring Decimal

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

  3. 【原创】leetCodeOj --- Fraction to Recurring Decimal 解题报告

    原题地址: https://oj.leetcode.com/problems/fraction-to-recurring-decimal/ 题目内容: Given two integers repre ...

  4. ✡ leetcode 166. Fraction to Recurring Decimal 分数转换 --------- java

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

  5. Leetcode#166 Fraction to Recurring Decimal

    原题地址 计算循环小数 先把负数转化成正数,然后计算,最后添加符号 当被除数重复出现的时候,说明开始循环了,所以用一个map保存所有遇到的被除数 需要考虑溢出问题,这也是本题最恶心的地方,看看通过率吧 ...

  6. 【LeetCode】166. Fraction to Recurring Decimal

    Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fra ...

  7. 【刷题-LeetCode】166 Fraction to Recurring Decimal

    Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fra ...

  8. 【leetcode】Fraction to Recurring Decimal

    Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fra ...

  9. 166. Fraction to Recurring Decimal

    题目: Given two integers representing the numerator and denominator of a fraction, return the fraction ...

随机推荐

  1. Ubuntu16.04安装 2.8.5版本Ansible

    wget https://bootstrap.pypa.io/pip/2.7/get-pip.py && python get-pip.py pip install --upgrade ...

  2. day10 负载均衡

    day10 负载均衡 负载均衡反向代理 正向代理:即是客户端代理, 代理客户端, 服务端不知道实际发起请求的客户端. # (内部上网) 客户端 <-> 代理 -> 服务端 反向代理即 ...

  3. flink-----实时项目---day06-------1. 获取窗口迟到的数据 2.双流join(inner join和left join(有点小问题)) 3 订单Join案例(订单数据接入到kafka,订单数据的join实现,订单数据和迟到数据join的实现)

    1. 获取窗口迟到的数据 主要流程就是给迟到的数据打上标签,然后使用相应窗口流的实例调用sideOutputLateData(lateDataTag),从而获得窗口迟到的数据,进而进行相关的计算,具体 ...

  4. HTTP 之 options预请求

    一.HTTP一共有八种常见请求方法 get:参数在url上,浏览器长度有限制,不安全 post:参数不可见,长度不受限制 put:上传最新内容到指定位置 delete:删除请求的url所表示的资源 h ...

  5. 【STM8】SPI通讯

    这篇内容有点长,如果有人想透过我的博客学习STM8的SPI,那是我的荣幸 首先我要先说大纲,这样大家心里比较有底,可以把精力都用在SPI理解上 [SPI初步介绍]:介绍SPI如何接线.名称解释.通讯注 ...

  6. C++ 数字分类

           1012 数字分类 (20分) 输入格式: 每个输入包含 1 个测试用例.每个测试用例先给出一个不超过 1000 的正整数 N,随后给出 N 个不超过 1000 的待分类的正整数.数字间 ...

  7. redis安装与简单实用

    1.在Linux上redis的安装时十分简单的: 第一步:wget http://download.redis.io/releases/redis-2.8.12.tar.gz 解压: tar zxvf ...

  8. Linux学习 - 文件特殊权限

    一.SUID权限(只针对文件) 只有可执行的二进制程序才能设定SUID权限 命令执行者要对该程序拥有x(执行)权限 1 拥有SUID的文件 /usr/bin/passwd 2 功能: 命令执行者(其他 ...

  9. wsdl实例

    1 <?xml version='1.0' encoding='UTF-8'?> 2 <wsdl:definitions name="HelloWorldService&q ...

  10. SQL 父子表,显示表中每条记录所在层级

    1.sqlserer 中有一张父子关系表,表结构如下: CREATE TABLE [dbo].[testparent]( [ID] [int] IDENTITY(1,1) NOT NULL, [nam ...