【LeetCode】#166分数到小数(Fraction to Recurring Decimal)
题目描述
给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。
如果小数部分为循环小数,则将循环的部分括在括号内。
示例
示例 1:
输入: numerator = 1, denominator = 2
输出: “0.5”
示例 2:
输入: numerator = 2, denominator = 1
输出: “2”
示例 3:
输入: numerator = 2, denominator = 3
输出: “0.(6)”
Description
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
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)”
解法
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
HashMap<Long, Integer> map = new HashMap<>();
List<Long> number = new ArrayList<>();
int index = 0;
int beginIndex = -1;
StringBuilder sb = new StringBuilder();
if(denominator==0)
return "";
long num = numerator;
long denum = denominator;
if(num<0 && denum>0 || (num>0 && denum<0)){
sb.append("-");
}
num = Math.abs(num);
denum = Math.abs(denum);
long val = num / denum;
sb.append(String.valueOf(val));
num = (num%denum)*10;
while(num!=0){
if(map.containsKey(num)){
beginIndex = map.get(num);
break;
}else{
map.put(num, index++);
val = num / denum;
num = (num%denum)*10;
number.add(val);
}
}
for(int i=0; i<index; i++){
if(i==0){
sb.append(".");
}
if(i==beginIndex){
sb.append("(");
}
sb.append(number.get(i));
}
if(beginIndex!=-1){
sb.append(")");
}
return sb.toString();
}
}