Problem:
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)"
Analysis:
本题的思路是模拟除法运算,但是需要记住每次小数运算的结果,一旦出现重复的数字那么它就可能会出现循环小数,使用Map来记录,此时也就可以终止运算。代码如下:
Code:
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
StringBuilder sb = new StringBuilder();
int gcd = Gcd(numerator, denominator);
long nu = Math.abs((long)numerator/gcd);
long de = Math.abs((long)denominator/gcd);
Map<Long, Integer> temp = new HashMap<Long, Integer>();
sb.append(String.valueOf(nu/de));
nu = nu%de;
if(nu != 0)
sb.append(".");
int cnt = sb.length() - 1;
while(nu != 0) {
long ans = nu * 10;
if(!temp.containsKey(nu)) {
cnt++;
sb.append(String.valueOf(ans/de));
temp.put(nu, cnt);
} else {
sb.insert(temp.get(nu), "(");
sb.append(")");
break;
}
nu = ans%de;
}
if((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0)) {
sb.insert(0, "-");
}
return sb.toString();
}
private int Gcd(int a, int b) {
while(b != 0) {
int temp = b;
b = a%b;
a = temp;
}
return a;
}
}
本文详细解析了将任意两个整数表示的分数转换为字符串格式的算法,重点介绍了如何识别并处理循环小数部分,通过使用Map数据结构记录运算过程,确保准确捕捉重复的数字序列。
196

被折叠的 条评论
为什么被折叠?



