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)".
这道题和divide two integer那道题不同,这道题可以直接使用除号和取模运算。但应该注意的是abs在使用前一定要将数据先转为long型。否则对于int型的minvalue会失效。这道题和divide two integer测试数据不同的是 输入-2147483648, -1会输出2147483648,不会溢出成maxvlue,所以不用管这个特殊情况。另外注意hashmap没存值时初始为null而非0。
Source
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();
}
}
Test
public static void main(String[] args){
int n = -2147483648, d = 1;
System.out.println(new Solution().fractionToDecimal(n, d));
}