Leetcode 题目解析之 Fraction to Recurring Decimal
【摘要】 Leetcode 题目解析之 Fraction to Recurring Decimal
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)”.
public String fractionToDecimal(int numerator, int denominator) {
String sign = "";
if (Math.signum(numerator) * Math.signum(denominator) < 0) {
sign = "-";
}
long n = Math.abs(numerator);
long d = Math.abs(denominator);
String intPart = Math.abs(n / d) + "";
// 如果整除,直接返回结果
if (n % d == 0) {
return sign + intPart;
}
// 计算小数部分
n %= d;
n *= 10;
StringBuilder sb = new StringBuilder();
Map<Long, Integer> mod = new HashMap<Long, Integer>();
for (int i = 0; n != 0; i++) {
long q = n / d;
Integer start = mod.get(n / 10);
if (start != null) {
sb.insert(start, "(");
sb.append(")");
break;
}
sb.append(Math.abs(q));
mod.put(n / 10, i);
n %= d;
n *= 10;
}
String fractionalPart = sb.toString();
return sign + intPart + "." + fractionalPart;
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)