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. Java并发包--ConcurrentHashMap原理解析

    ConcurrentHashMap实现原理及源码分析   ConcurrentHashMap是Java并发包中提供的一个线程安全且高效的HashMap实现(若对HashMap的实现原理还不甚了解,可参 ...

  2. Linux下干净卸载mysql

    1.首先查看mysql的安装情况 rpm -qa|grep -i mysql 显示之前安装了: MySQL-client-5.5.25a-1.rhel5 MySQL-server-5.5.25a-1. ...

  3. 第119题:杨辉三角II

    一. 问题描述 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行. 在杨辉三角中,每个数是它左上方和右上方的数的和. 示例: 输入: 3 输出: [1,3,3,1] 二. 解题思路 ...

  4. C# 调用cmd执行命令

    private void CmdRun_Click(object sender, EventArgs e)        {            Process p = new Process(); ...

  5. [GraphQL] Reuse GraphQL Selection Sets with Fragments

    Fragments are selection sets that can be used across multiple queries. They allow you to refactor re ...

  6. MySQL Multi-Range Read(MRR 索引多范围查找) 原理与解析

    原理: 如果基表很大,数据没有被缓存,在二级索引上使用范围扫描读取行可能会导致大量的随机磁盘访问.使用Multi-Range Read新特性,mysql可以减少对磁盘的随机读的次数:首先,mysql只 ...

  7. [USACO08FEB]酒店Hotel 线段树

    [USACO08FEB]酒店Hotel 线段树 题面 其实就是区间多维护一个lmax,rmax(表示从左开始有连续lmax个空房,一直有连续rmax个空房到最右边),合并时讨论一下即可. void p ...

  8. Centos7.x 安装 Supervisord

    [环境] 系统:Centos 7.3 软件:supervisord [安装Supervisord] yum install epel-release yum install -y supervisor ...

  9. Python基础之定义有默认参数的函数

    1. 构建有默认参数的函数 当我们在构建一个函数或者方法时,如果想使函数中的一个或者多个参数使可选的,并且有一个默认值,那么可以在函数定义中给参数指定一个默认值,并且放到参数列表的最后就行了.比如: ...

  10. C++标准库分析总结(二)——<模板,分配器,List>

    本节主要总结模板及其类模板分类以及STL里面的分配器.容器内部结构以及容器之间的关系和分类,还介绍了容器中List的结构分布 1.源代码版本介绍 1.1 VC的编译器源码目录: 2.类模板 2.1 类 ...