[LeetCode] 167. 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.
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 题目汇总
[LeetCode] 167. Fraction to Recurring Decimal 分数转循环小数的更多相关文章
- [LeetCode] Fraction to Recurring Decimal 分数转循环小数
Given two integers representing the numerator and denominator of a fraction, return the fraction in ...
- ✡ leetcode 166. Fraction to Recurring Decimal 分数转换 --------- java
Given two integers representing the numerator and denominator of a fraction, return the fraction in ...
- Leetcode 166. Fraction to Recurring Decimal 弗洛伊德判环
分数转小数,要求输出循环小数 如2 3 输出0.(6) 弗洛伊德判环的原理是在一个圈里,如果一个人的速度是另一个人的两倍,那个人就能追上另一个人.代码中one就是速度1的人,而two就是速度为2的人. ...
- 【leetcode】Fraction to Recurring Decimal
Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fra ...
- Java for LeetCode 166 Fraction to Recurring Decimal
Given two integers representing the numerator and denominator of a fraction, return the fraction in ...
- [LeetCode#116]Fraction to Recurring Decimal
Problem: Given two integers representing the numerator and denominator of a fraction, return the fra ...
- 166 Fraction to Recurring Decimal 分数到小数
给定两个整数,分别表示分数的分子和分母,返回字符串格式的小数.如果小数部分为循环小数,则将重复部分括在括号内.例如, 给出 分子 = 1, 分母 = 2,返回 "0.5". ...
- Leetcode166. Fraction to Recurring Decimal分数到小数
给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数. 如果小数部分为循环小数,则将循环的部分括在括号内. 示例 1: 输入: numerator ...
- Leetcode#166 Fraction to Recurring Decimal
原题地址 计算循环小数 先把负数转化成正数,然后计算,最后添加符号 当被除数重复出现的时候,说明开始循环了,所以用一个map保存所有遇到的被除数 需要考虑溢出问题,这也是本题最恶心的地方,看看通过率吧 ...
随机推荐
- 表单中submit和button按钮的区别!
对于表单的按钮以前知道submit和button有区别,但没有深入探索,今天刚好又碰到这个问题,看了下网络上这位朋友已经有现成的总结了,而且比较到位,拿来跟大家分享下(原文地址:http://blog ...
- dede织梦调用顶级二级栏目及下三级栏目方法(数据库实现)
上次有说道能调用织梦的二级栏目今天来说道说道调用三级,乃至无限极 ①:通过dede调用二级栏目大家都会调用,但要调用三级栏目,就有点麻烦了,如下样式的三级栏目dede如何调用呢?如下: ------- ...
- Copy Books
Description Given n books and the i-th book has pages[i] pages. There are k persons to copy these bo ...
- 小程序官方基础项目api请求
onLaunch: function () { // 展示本地存储能力 var logs = wx.getStorageSync('logs') || [] logs.unshift(Date.now ...
- 后缀数组 TYVJ P1860 后缀数组
/*P1860 后缀数组时间: 1000ms / 空间: 131072KiB / Java类名: Main描述 我们定义一个字符串的后缀suffix(i)表示从s[i]到s[length(s)]这段子 ...
- LibreOJ #6217. 扑克牌
二次联通门 : LibreOJ #6217. 扑克牌 /* LibreOJ #6217. 扑克牌 背包.... 回到家之后简直了...sb题想半天 */ #include <cstdio> ...
- Mac cpu过高问题分析及解决
1.mds.mds_stores.mdworker 关闭: sudo mdutil -a -i off 打开: sudo mdutil -a -i on
- 安装cartographer遇到Unrecognized syntax identifier "proto3". This parser only recognizes "proto2"问题
https://stackoverflow.com/questions/38605734/mac-cannot-find-eigen3 https://blog.csdn.net/qq_4214518 ...
- Codeforces Round #566 (Div. 2)题解
时间\(9.05\)好评 A Filling Shapes 宽度为\(3\),不能横向填 考虑纵向填,长度为\(2\)为一块,填法有两种 如果长度为奇数则显然无解,否则\(2^{n/2}\) B Pl ...
- 小程序 之eval替代方案(Binding.js)
一.下载 链接:https://pan.baidu.com/s/1D6vNSSBZI22_K1BzLEXpbg提取码:of6g 修改binding.js中的window.bind=binding为如下 ...