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记录每次除数的位置,但是除数有可能存在连续几个0的情况,所以是有问题的,正确的方法是map记录每次余数的位置。
题目的几个坑:除数为0、被除数为0、正好整除无小数、商是负数以及商溢出的这几种情况都要考虑到。
先放自己有问题的代码:
public String fractionToDecimal(int numerator, int denominator) {
if (denominator == 0) {
return String.valueOf(Integer.MAX_VALUE);
}
if (numerator == 0) {
return "0";
}
boolean negative = false;
if ((numerator > 0 && denominator < 0) || (numerator < 0 && denominator > 0)) {
negative = true;
}
numerator = Math.abs(numerator);
denominator = Math.abs(denominator);
int dotLeft = numerator / denominator;
int yushu = numerator % denominator;
if (yushu == 0) {
return String.valueOf(dotLeft);
}
String dotRight = "";
int[] map = new int[10];
int cnt = 1;
while (yushu > 0) {
int cur = yushu * 10;
int devide = cur / denominator;
if (map[devide] > 0) {
dotRight = dotRight.substring(0, map[devide]-1) + "(" + dotRight.substring(map[devide]-1) + ")";
break;
}
dotRight += String.valueOf(devide);
map[devide] = cnt;
yushu = cur % denominator;
cnt++;
}
return (negative ? "-" : "") + String.valueOf(dotLeft) + "." + String.valueOf(dotRight);
}
下面是solution给出的标准解答,对比起来自己的代码丑哭了。。。
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder fraction = new StringBuilder();
// If either one is negative (not both)
if (numerator < 0 ^ denominator < 0) {
fraction.append("-");
}
// Convert to Long or else abs(-2147483648) overflows
long dividend = Math.abs(Long.valueOf(numerator));
long divisor = Math.abs(Long.valueOf(denominator));
fraction.append(String.valueOf(dividend / divisor));
long remainder = dividend % divisor;
if (remainder == 0) {
return fraction.toString();
}
fraction.append(".");
Map<Long, Integer> map = new HashMap<>();
while (remainder != 0) {
if (map.containsKey(remainder)) {
fraction.insert(map.get(remainder), "(");
fraction.append(")");
break;
}
map.put(remainder, fraction.length());
remainder *= 10;
fraction.append(String.valueOf(remainder / divisor));
remainder %= divisor;
}
return fraction.toString();
}