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,
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
题意:将分数转换成小数
思路:用HashMap存已经计算过的分子,如果一个新的分子存在map中,则出现循环,因此用分子作为map的key就行。但是对于map的value该怎么定,出现了疑惑。
1. 用分子除以分母的整数值作为value,之后如果出现循环,只要看循环开始的value是什么,找到对应的位置插入()就好了,但是在1/90的case中出现问题;
2. 看到别人的代码中用不同分子时,对应的结果长度作为value,这样可以避免1中出现的问题;所以用这种方式报错value值。
可能会挂掉的case:
0/11
1/90;
1/2147483647(Integer.MAX_VALUE);
-1/2147483647;
1/-2147483638;
代码如下:
public String fractionToDecimal(int a1, int a2) { if(a1 == 0 || a2 == 0) return "0"; StringBuilder sb = new StringBuilder(); sb.append((a1>0) ^ (a2>0) ? "-":""); long a = Math.abs((long)a1); long b = Math.abs((long)a2); sb.append(Math.abs(a/b)); a = (a % b) * 10; if(a != 0) sb.append("."); Map<Long, Integer> map = new HashMap<Long, Integer>(); map.put(new Long(a1), sb.length()); while(a != 0) { sb.append(a/b); map.put(a, sb.length()); a = (a % b) * 10; if(map.containsKey(a)) { int pos = map.get(a); sb.insert(pos-1, "("); sb.append(")"); break; } } return sb.toString(); }
在上述代码中,把输入转换为long类型进行计算的原因是:
1. 存在*10计算,用int可能会溢出;
2. 把Integer.MIN_VALUE转换为正数时,如果用int类型还是会溢出;
LeetCode-166 Fraction to Recurring Decimal
原文:http://www.cnblogs.com/linxiong/p/4450085.html