leetcode: Fraction to Recurring Decimal
来源:互联网 发布:淘宝宝贝被删除怎么办 编辑:程序博客网 时间:2024/05/22 05:07
<span style="font-family: Arial, Helvetica, sans-serif;">public class Solution {</span>
public String fractionToDecimal(int numerator, int denominator) { if( numerator==0 ) { return "0"; } if( denominator==0 ) { return ""; } String ret = ""; long num = numerator,den = denominator; if( num%den == 0 ) { return (num/den)+""; } boolean flag = true; if( numerator==Integer.MIN_VALUE && denominator>0 ) { ret += "-"; } else if( denominator==Integer.MIN_VALUE && numerator>0 ) { ret += "-"; } else if( (denominator<0&&numerator>0)||(denominator>0&&numerator<0) ) { ret += "-"; } num = Math.abs(num); den = Math.abs(den); long tmp = num/den; ret += tmp + "."; long left = (num%den)*10; HashMap<Long,Integer> m = new HashMap<Long,Integer>(); while(left>0) { if(m.containsKey(left)) { int st = m.get(left); String s1 = ret.substring(0,st); String s2 = ret.substring(st,ret.length()); ret = s1+'('+s2+')'; return ret; } m.put(left,ret.length()); tmp = left/den; ret += tmp; left = (left%den)*10; } return ret; }}
要求输入除数和被除数,用string形式将结果表示出来,循环小数用括号包围...
实际上我们可以利用整除和求余来判断是否有小数以及结果的正数部分。为了应对大测试数据,题目中全部换为了long型计算....
对于小数点后的计算,我们可以不断的将余数乘以10后再除以除数一位位的求出小数点后的各位...我们知道当且仅当小数点后的各位中出现了相同的数字,结果是循环小数,循环部分为两个相同数字之间的各位...我们可以利用map存小数点后的各位,key为当前位代表的余数,value为位数...while中出现重复时,利用substring函数即可取出循环各位按结果输出。
PS:由于大整数问题,最好全部转为long再做判断....网易云笔记真是垃圾
0 0
- [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
- leetcode: Fraction to Recurring Decimal
- UIActivityIndicatorView的属性和用法
- activemq发送和接收对象
- 如何查看java源码中的native方法源码
- Linux 进程组,作业,会话的理解
- 支持向量分类实用指南
- leetcode: Fraction to Recurring Decimal
- iOS应用内置付费In-App Purchases入门
- ext2 文件系统
- PhoneGap开发环境搭建
- 查看oracle数据库的sid
- (zz)actors角色模型系列之一 actors介绍以及akka 框架的使用入门
- MATLAB 调用编译.c/.cpp文件
- CodeForces 519E A and B and Lecture Rooms
- save the transient instance before flushing