leetCode 166. Fraction to Recurring Decimal
来源:互联网 发布:网络用语128是什么意思 编辑:程序博客网 时间:2024/06/16 04:26
1.题目
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)”.
题目的基本意思是给出分子和分母,求出表示的数。如果是无限循环小数,用括号把循环体括起来
2.算法
这题的思路是依次除以除数,并对除数取余,然后得到下一位,如果余数为0,说明不是无限循环小数,如果有两个余数相同,就是循环小数,然后找出循环的位置,加上括号
public class Solution { public String fractionToDecimal(int numerator, int denominator) { if (numerator == 0) return new String("0"); boolean flag = (numerator < 0)^(denominator < 0); long Numerator = Math.abs((long)numerator); long Denominator = Math.abs((long)denominator); StringBuffer res = new StringBuffer(); if (flag == true) res.append('-'); res.append(String.valueOf((Numerator / Denominator))); Numerator = Numerator % Denominator; if (Numerator == 0) return res.toString(); res.append('.'); HashMap<Long, Integer> map = new HashMap<Long, Integer>(); for (int i = res.length(); Numerator != 0; ++i) { if (map.get(Numerator) != null) break; map.put(Numerator, i); Numerator *= 10; res.append(String.valueOf((Numerator / Denominator))); Numerator %= Denominator; } if (Numerator == 0) return res.toString(); res.insert(map.get(Numerator),"("); res.append(')'); return res.toString();}
0 0
- 166. Fraction to Recurring Decimal Leetcode Python
- Leetcode-166.Fraction to Recurring Decimal
- [Leetcode]166. Fraction to Recurring Decimal @python
- [leetcode] 166. Fraction to Recurring Decimal
- leetcode 166. Fraction to Recurring Decimal
- [LeetCode]166. Fraction to Recurring Decimal
- LeetCode *** 166. Fraction to Recurring Decimal
- LeetCode 166. Fraction to Recurring Decimal
- [LeetCode]problem 166. Fraction to Recurring Decimal
- leetcode-java-166. Fraction to Recurring Decimal
- LeetCode 166. Fraction to Recurring Decimal
- [LeetCode] 166. Fraction to Recurring Decimal
- Leetcode-166. Fraction to Recurring Decimal
- leetcode 166. Fraction to Recurring Decimal
- Leetcode 166. Fraction to Recurring Decimal
- LeetCode 166. Fraction to Recurring Decimal
- Leetcode 166. Fraction to Recurring Decimal
- leetCode 166. Fraction to Recurring Decimal
- 引用类型方法传参的一点领悟
- 使用TCP-IP Monitor监视Soap协议
- 毛玻璃效果
- 直播技术
- 视频基础
- leetCode 166. Fraction to Recurring Decimal
- H.265(HEVC)深度解析
- 非对称加密算法DH
- 剑指offer:旋转数组的最小位置
- myeclipse中设置hibernate.cfg.xml提示
- pentaho 以固定形式显示报表
- 数据链路层
- Android多点触控实例
- C# 代码写ComboBox控件