LeetCode Fraction to Recurring Decimal
2016-06-04 21:52
896 查看
LeetCode解题之Fraction to Recurring Decimal
原题
将一个分数用小数的形式表示,如果小数部分存在循环,将循环的部分放在圆括号内来表示无限循环。注意点:
无
例子:
输入: numerator = 1, denominator = 2
输出: “0.5”
输入: numerator = 2, denominator = 3
输出: “0.(6)”
解题思路
能够除尽的很简单,就是模拟一个除法操作,对于无限循环小数,如果哪一次的余数在之前已经出现过了,那么继续算下去就会出现循环,这时候就可以停止运算,并将这两位之间的数添加到括号中。整数部分不存在循环问题,所以可以先单独计算,符号也可以先确定。因为是判断是否有重复的余数,对于能够除尽的情况,重复的余数是除尽后的0,所以末尾会多个”(0)”,要去掉。而能够整除的情况,要把小数点也去掉。AC源码
class Solution(object): def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ sign = '-' if numerator * denominator < 0 else '' quotient, remainder = divmod(abs(numerator), abs(denominator)) result_list = [sign, str(quotient), '.'] remainders = [] while remainder not in remainders: remainders.append(remainder) quotient, remainder = divmod(remainder * 10, abs(denominator)) result_list.append(str(quotient)) idx = remainders.index(remainder) result_list.insert(idx + 3, '(') result_list.append(')') result = ''.join(result_list).replace('(0)', '').rstrip('.') return result if __name__ == "__main__": assert Solution().fractionToDecimal(1, 2) == '0.5' assert Solution().fractionToDecimal(2, 1) == '2' assert Solution().fractionToDecimal(2, 3) == '0.(6)'
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法