【LeetCode】008 Fraction to Recurring Decimal 六点六六六循环
来源:互联网 发布:添加json里的一个对象 编辑:程序博客网 时间:2024/05/16 12:02
【题目】
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.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
给定分子分母,返回其小数形式,若为无限循环小数,则用括号标出循环部分。
点击打开链接
【解析】
设res为最终输出字符串。m[r]为res中每一位数字所在单元的标号。每次做除法得到的余数r即为res在该位置上的数字,查找r是否在m集合中,若不在其中则继续进行除法运算,若在其中则说明进入循环,从m[r]中提取位数,将res中之前的字符保留,将res中m[r]以后的字符放入括号内,最后整个字符串赋值给res更新。
【程序】
python版本
class Solution(object): def fractionToDecimal(self, numerator, demoinator):res = ''if numerator == 0:return str(0)elif (numerator < 0) ^ (demoinator < 0):res += '-'n = abs(numerator)d = abs(demoinator)res += str(n//d)if n % d == 0:return resres += '.'r = n % dm = {}while r:if r in m:res = res[:m[r]] + '('+res[m[r]:]+')'breakm[r] = len(res)r *= 10res += str(r//d)r %= d return res
res[:n]表示截取res字符串中,res[n]以前所有字符;res[n:]表示截取res字符串中,res[n]以后所有字符(包括res[n])。
【关于bug】在Python中,‘/’表示正常除法,‘//’表示整除,区别于c语言。若使用正常除法,在res字符串内会出现浮点数,造成结果出错。
- 【LeetCode】008 Fraction to Recurring Decimal 六点六六六循环
- [leetcode] Fraction to Recurring Decimal
- LeetCode Fraction to Recurring Decimal
- Fraction to Recurring Decimal leetcode
- leetcode:Fraction to Recurring Decimal
- [LeetCode] Fraction to Recurring Decimal
- [leetCode] Fraction to Recurring Decimal
- LeetCode:Fraction to Recurring Decimal
- Leetcode: Fraction to Recurring Decimal
- Leetcode: Fraction to Recurring Decimal
- [LeetCode] Fraction to Recurring Decimal
- [LeetCode]Fraction to Recurring Decimal
- leetcode:Fraction to Recurring Decimal
- [LeetCode]Fraction to Recurring Decimal
- Leetcode: Fraction to Recurring Decimal
- [leetcode]Fraction to Recurring Decimal
- LeetCode: Fraction to Recurring Decimal
- [LeetCode] Fraction to Recurring Decimal
- <%@ page isELIgnored="false"%>的作用
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 四次元新浪微博客户端Android源码
- BZOJ 2152 聪聪可可 [树分治 or 树形DP]
- Android binder (2): Parcel
- 【LeetCode】008 Fraction to Recurring Decimal 六点六六六循环
- 密码
- hd 1070 Milk
- Android binder (3): Binder 驱动的初始化
- tableview滚动的时候cell的分割线一会粗一会细的问题
- ping不通Linux系统解决方法
- Android Studio集成极光推送(Jpush) 报错 java.lang.UnsatisfiedLinkError: cn.jpush.android.service.PushProtocol
- 关于数组指针,字符串指针的一些小细节
- Servlet运行路径问题的解决