https://leetcode.com/problems/fraction-to-recurring-decimal/
给定一个除数,一个被除数,用string表示他们的返回值,如果出现了循环,则用"()"代替
- 思路
用跟乘法的类似原理,也是用每一次的除法的值和余数来循环,有一个前提条件是,能写成分数的小数一定是有理数,换言之,不会出现不规律的无限循环。
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder fraction = new StringBuilder();
//只有当一个为正,一个为负
//true ^ false = true
if (numerator < 0 ^ denominator < 0) {
fraction.append("-");
}
//转化成long
long dividend = Math.abs(Long.valueOf(numerator));
long divisor = Math.abs(Long.valueOf(denominator));
//小数点前的那一位,直接用除法可以得到
fraction.append(String.valueOf(dividend / divisor));
long remainder = dividend % divisor;
//除完余数为0,直接返回,不用计算小数点后面的值
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();
}
网友评论