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 分数转循环小数的更多相关文章

  1. [LeetCode] Fraction to Recurring Decimal 分数转循环小数

    Given two integers representing the numerator and denominator of a fraction, return the fraction in ...

  2. ✡ leetcode 166. Fraction to Recurring Decimal 分数转换 --------- java

    Given two integers representing the numerator and denominator of a fraction, return the fraction in ...

  3. Leetcode 166. Fraction to Recurring Decimal 弗洛伊德判环

    分数转小数,要求输出循环小数 如2 3 输出0.(6) 弗洛伊德判环的原理是在一个圈里,如果一个人的速度是另一个人的两倍,那个人就能追上另一个人.代码中one就是速度1的人,而two就是速度为2的人. ...

  4. 【leetcode】Fraction to Recurring Decimal

    Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fra ...

  5. Java for LeetCode 166 Fraction to Recurring Decimal

    Given two integers representing the numerator and denominator of a fraction, return the fraction in ...

  6. [LeetCode#116]Fraction to Recurring Decimal

    Problem: Given two integers representing the numerator and denominator of a fraction, return the fra ...

  7. 166 Fraction to Recurring Decimal 分数到小数

    给定两个整数,分别表示分数的分子和分母,返回字符串格式的小数.如果小数部分为循环小数,则将重复部分括在括号内.例如,    给出 分子 = 1, 分母 = 2,返回 "0.5".  ...

  8. Leetcode166. Fraction to Recurring Decimal分数到小数

    给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数. 如果小数部分为循环小数,则将循环的部分括在括号内. 示例 1: 输入: numerator ...

  9. Leetcode#166 Fraction to Recurring Decimal

    原题地址 计算循环小数 先把负数转化成正数,然后计算,最后添加符号 当被除数重复出现的时候,说明开始循环了,所以用一个map保存所有遇到的被除数 需要考虑溢出问题,这也是本题最恶心的地方,看看通过率吧 ...

随机推荐

  1. Selenium3学习中遇到的问题

    pytesseract识别验证码 TesseractNotFoundError: tesseract is not installed or it's not in your path brew in ...

  2. Maximum Subarray II

    Given an array of integers, find two non-overlapping subarrays which have the largest sum. The numbe ...

  3. 使用jQuery快速高效制作网页交互特效----jQuery中的事件与动画

    jQuery中的事件 和WinForm一样,在网页中的交互也是需要事件来实现的,例如tab切换效果,可以通过鼠标单击事件来实现. 事件在元素对象与功能代码中起着重要的桥梁作用. 在JQuery中,事件 ...

  4. javascript权威指南第16章 HTML5脚本编程

    <!DOCTYPE html> <html> <head> <script type="text/javascript" src=&quo ...

  5. 2019年京东 PHP工程师面试题

    1. Apache与Nginx大访问下性能描述正确的是? A.Apache所采用的epoll网络I/O模型非常高效B.Nginx使用了最新的kqueue和select网络I/O模型C.Apache进程 ...

  6. 12 | 为什么我的MySQL会“抖”一下?

    平时的工作中,不知道你有没有遇到过这样的场景,一条SQL语句,正常执行的时候特别快,但是有时也不知道怎么回事,它就会变得特别慢,并且这样的场景很难复现,它不只随机,而且持续时间还很短. 看上去,这就像 ...

  7. 数据结构实验之二叉树六:哈夫曼编码(SDUT 3345)

    题解:离散中的"最小生成树(最优树)". #include <bits/stdc++.h> using namespace std; void qusort(int l ...

  8. Ubuntu 16.04安装完重启后黑屏,光标一直闪

    原文:https://blog.csdn.net/weixin_38533896/article/details/81023690 版权声明:本文为博主原创文章,转载请附上博文链接! 安装教程网址:h ...

  9. golang ssh 远程执行命令(有一些命令会报command not found)

    func sshSession(user, password, host string, port int) (sshSession *ssh.Session, err error) { //参数: ...

  10. go struct 自定义标签获取

    package main import ( "fmt" "reflect" ) type Test struct { Id int `json:"us ...