166. Fraction to Recurring Decimal
来源:互联网 发布:企业即时聊天软件 编辑:程序博客网 时间:2024/06/05 20:46
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)”.
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
class Solution { public String fractionToDecimal(int numerator, int denominator) { if (numerator == 0) return "0"; if (denominator == 0) return ""; String ans = ""; //如果结果为负数 if ((numerator < 0) ^ (denominator < 0)) { ans += "-"; } //下面要把两个数都转为正数,为避免溢出,int转为long long num = numerator, den = denominator; num = Math.abs(num); den = Math.abs(den); //结果的整数部分 long res = num / den; ans += String.valueOf(res); //如果能够整除,返回结果 long rem = (num % den) * 10; if (rem == 0) return ans; //结果的小数部分 HashMap<Long, Integer> map = new HashMap<Long, Integer>(); ans += "."; while (rem != 0) { //如果前面已经出现过该余数,那么将会开始循环 if (map.containsKey(rem)) { int beg = map.get(rem); //循环体开始的位置 String part1 = ans.substring(0, beg); String part2 = ans.substring(beg, ans.length()); ans = part1 + "(" + part2 + ")"; return ans; } //继续往下除 map.put(rem, ans.length()); res = rem / den; ans += String.valueOf(res); rem = (rem % den) * 10; } return ans; }}
阅读全文
0 0
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 有关于原创功能的一切问题,看这里就OK!
- qt4 代码 转换为 qt5
- [codefoces519E]A and B and Lecture Rooms(lca)
- 【深度学习】入门理解ResNet和他的小姨子们(二)---DenseNet
- 蜜汁最大完全平方数
- 166. Fraction to Recurring Decimal
- Android 使用多线程来做多文件上传Or下载
- Mac创建一个IPV6 Wifi热点
- Light Oj-1245
- 最大子序列和
- Qt::ConnectionType 解析
- 实测 c# .net 中 httpwebrequest 和 httpclient 性能 区别 对比
- Linux下MySQL的简单使用(3)
- JAVA数组