[LeetCode] 167. Fraction to Recurring Decimal 分数转循环小数
2024-08-24 16:31:10
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)"
给2个整数分别作分子和分母,返回分数的字符串形式。
Java:
public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder res = new StringBuilder();
// "+" or "-"
res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator); // integral part
res.append(num / den);
num %= den;
if (num == 0) {
return res.toString();
} // fractional part
res.append(".");
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
map.put(num, res.length());
while (num != 0) {
num *= 10;
res.append(num / den);
num %= den;
if (map.containsKey(num)) {
int index = map.get(num);
res.insert(index, "(");
res.append(")");
break;
}
else {
map.put(num, res.length());
}
}
return res.toString();
}
}
Python:
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
result = ""
if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0):
result = "-" dvd, dvs = abs(numerator), abs(denominator)
result += str(dvd / dvs)
dvd %= dvs if dvd > 0:
result += "." lookup = {}
while dvd and dvd not in lookup:
lookup[dvd] = len(result)
dvd *= 10
result += str(dvd / dvs)
dvd %= dvs if dvd in lookup:
result = result[:lookup[dvd]] + "(" + result[lookup[dvd]:] + ")" return result
C++:
// upgraded parameter types
string fractionToDecimal(int64_t n, int64_t d) {
// zero numerator
if (n == 0) return "0"; string res;
// determine the sign
if (n < 0 ^ d < 0) res += '-'; // remove sign of operands
n = abs(n), d = abs(d); // append integral part
res += to_string(n / d); // in case no fractional part
if (n % d == 0) return res; res += '.'; unordered_map<int, int> map; // simulate the division process
for (int64_t r = n % d; r; r %= d) { // meet a known remainder
// so we reach the end of the repeating part
if (map.count(r) > 0) {
res.insert(map[r], 1, '(');
res += ')';
break;
} // the remainder is first seen
// remember the current position for it
map[r] = res.size(); r *= 10; // append the quotient digit
res += to_string(r / d);
} return res;
}
All LeetCode Questions List 题目汇总
最新文章
- Centos6.5搭建java开发环境
- Selenium_模拟淘宝登录Demo
- SqlDataReader执行带输出参数存储过程 错误分析
- struts2中的addActionError 、addFieldError、addActionMessage的方法
- Andorid面试问题整理
- 树形dp求树的重心
- WebApi传递JSON参数
- 【Tips】Endnote导入IEEE Xplore文献方法《转载》
- [Cacti] memcache安装执行、cacti监控memcache实战
- js经典闭包
- javaScript 验证码 倒计时60秒
- 处理eclipse启动时报java.lang.IllegalStateException
- OO期末总结
- Winform 关闭按钮
- npm cnpm
- sql先分组,再算百分比
- 使用spring-boot-maven-plugin插件打包spring boot项目
- 007-Shell test 命令,[],[[]]
- VS和IE或者360兼容模式简单调试js方法
- java 流 文件 IO