题目链接:https://leetcode.com/problems/fraction-to-recurring-decimal/
题目:
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)".
解题思路:
这题的考点是模拟除法运算。
关键就是处理循环小数部分。。。用hash表记录余数的位置。如果余数重复出现的话,那就是出现了循环小数。代码中使用HashMap来记录余数,以及余数在字符串中的位置。当第二次出现相同的余数时,说明出现了循环。
这题也包含了很多小细节:
1. 除数不为0
2. 除数或被除数有一者为负数时
3. 当 int 无法表示时,换成 long 类型
4. 当整数部分已经除尽没有小数部分时,不再添加小数点
有网友说这题在面google和facebook中遇到过。
代码实现:
public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if(denominator == 0) // 分母为0
return null;
StringBuilder sb = new StringBuilder();
if(numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0)
sb.append("-");
long numerator1 = Math.abs((long)numerator);
long denominator1 = Math.abs((long)denominator);
long quotien = numerator1 / denominator1;
long reminder = numerator1 % denominator1;
sb.append(quotien);
if(reminder == 0)
return sb.toString();
sb.append(".");
int i = sb.length();
HashMap<Long, Integer> map = new HashMap();
while(reminder != 0) {
if(map.containsKey(reminder)) {
int index = map.get(reminder);
sb.insert(index, "(");
sb.append(")");
break;
}
map.put(reminder, i);
sb.append(reminder * 10 / denominator1);
reminder = reminder * 10 % denominator1;
i ++;
}
return sb.toString();
}
}
35 / 35 test cases passed.
Status: Accepted
Runtime: 3 ms