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)".
public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
long n = numerator, d = denominator;
if(n == 0) return "0";
StringBuffer a = new StringBuffer();
if((n < 0) ^ (d < 0)) a.append("-");
n = Math.abs(n);
d = Math.abs(d);
long in = n / d;
a.append(String.valueOf(in)); //StringBuffer裏面沒有String的 a = a +
if(n % d == 0) return a.toString();
else a.append(".");
//以上是小數點以前的
HashMap<Long, Integer> map = new HashMap<Long, Integer>(); //注意要用Long和Integer 不能用long和int
//用hashmap查找循環的地方比較方便
//System.out.println(map.get(0)); //打印可看出 integer位置上未初始化時存的是null
long i;
for(i = n % d; i != 0; i = i % d){ //注意step
if(map.get(i) != null) break;
map.put(i, a.length()); //將i的值當做key a的位置當做value
i *= 10;
a.append(i / d);
}
if(i == 0) return a.toString();
a.insert(map.get(i), "("); //直接在循環的地方加入(
a.append(")"); //出現循環就立即跳出了循環,也就是說從i的位置到最後,都是循環體,所以只需在最後面加上)
return a.toString();
}
}
public static void main(String[] args){
int n = -2147483648, d = 1;
System.out.println(new Solution().fractionToDecimal(n, d));
}