✡ leetcode 166. Fraction to Recurring Decimal 分数转换 --------- java

时间:2024-04-02 08:07:14

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)".

题意很简单,就是把分数转换成小数。

方法也没什么难的,就是利用HashMap来存储余数出现的位置,遇到相同余数,那么就是循环小数了。

需要注意的点:1、int的最小值,这个神烦,只能用long来存储计算。

       2、正负号

       3、整除没有小数点。

public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0){
return "0";
}
long num1 = Math.abs((long)numerator);
long num2 = Math.abs((long)denominator);
StringBuffer str = new StringBuffer();
if (numerator < 0 ^ denominator < 0 ){
str.append('-');
}
long div = num1 / num2;
long mod = num1 % num2;
if (mod == 0){
str.append(div);
return str.toString();
}
Map map = new HashMap<Long,Integer>();
str.append(div+".");
map.put(mod,str.length());
num1 = mod * 10;
while (mod != 0){
div = num1 / num2;
mod = num1 % num2;
str.append(div);
if (map.containsKey(mod)){
str.insert((int)map.get(mod),'(');
str.append(')');
return str.toString();
}
map.put(mod,str.length());
num1 = mod * 10;
}
return str.toString();
}
}