https://leetcode.com/problems/fraction-to-recurring-decimal/
要知道如何判断是否是循环小数,就是当前的余数是之前已经出现过的。因此想到用Hash。然后循环小数要用()隔开,因此用HashMap,key存当前余数,val存当前sb的长度,这样可以使得以后找到在哪里添加前括号(
另外还是强转型的问题,各种地方都用一下吧,反正不会死。
public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
StringBuilder sb = new StringBuilder();
sb.append((numerator > 0) ^ (denominator > 0) ? "-" : "");
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator);
// long den1 = (long)Math.abs(denominator); 这样得到的den1=-2147483648,是错的
System.out.print(den+","+den1);
sb.append(num / den);
num %= den;
if (num == 0) return sb.toString();
sb.append(".");
HashMap<Long, Integer> map = new HashMap<>();
map.put(num, sb.length());
while (num != 0) {
num *= 10;
sb.append(num / den);
num %= den;
if (map.containsKey(num)) {
int index = map.get(num);
sb.insert(index, "(");
sb.append(")");
break;
} else {
map.put(num, sb.length());
}
}
return sb.toString();
}
}