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.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:
Input: numerator = 2, denominator = 3
Output: "0.(6)"
思路:这题核心考点就是后面如何处理循环小数,解决方法就是用hashmap去存分子,只有相同的分子出现的时候,才会出现循环小数,而且注意的是:分子每次都是乘以10,来进行扩充,然后除以分母;
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
StringBuilder sb = new StringBuilder();
if((numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0)) {
sb.append("-");
}
long num = Math.abs((long) numerator);
long den = Math.abs((long) denominator);
sb.append(num / den);
num = num % den;
if(num == 0) {
return sb.toString();
}
sb.append(".");
// 存分子和sb的length,是为了出现重复,直接做substring, 0.456 123 123 第二个1出现的时候就可以把123括号了;
// num, len;
HashMap<Long, Integer> hashmap = new HashMap<>();
while(num > 0) {
if(!hashmap.containsKey(num)) {
hashmap.put(num, sb.toString().length());
} else {
int index = hashmap.get(num);
return sb.substring(0, index) + "(" + sb.substring(index) + ")";
}
num *= 10;
sb.append(num / den);
num = num % den;
}
return sb.toString();
}
}