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. Linux中drwxr-xr-x.的意思和权限

    转载:https://blog.csdn.net/weixin_39209728/article/details/79729885 读(read),写(write),执行r(recute)简写即为(r ...

  2. 通过自定义属性获取指定checkbox是否选中

    $("input[conferid='"+conferid+"']").is(':checked'); $("input[conferid='1234 ...

  3. 重载new和delete运算符

    内存管理运算符 new.new[].delete 和 delete[] 也可以进行重载,其重载形式既可以是类的成员函数,也可以是全局函数.一般情况下,内建的内存管理运算符就够用了,只有在需要自己管理内 ...

  4. BZOJ4406 WC2016 论战捆竹竿

    Problem BZOJ Solution 显然是一个同余系最短路问题,转移方案就是所有|S|-border的长度,有 \(O(n)\) 种,暴力跑dijkstra的复杂度为 \(O(n^2\log ...

  5. (7)打鸡儿教你Vue.js

    计算属性 computed <div id="app"> {{ message.split('').reverse().join('') }} </div> ...

  6. (6)打鸡儿教你Vue.js

    循环语句 循环使用 v-for 指令 <div id="app"> <ol> // 有序 <li v-for="item in items& ...

  7. zabbix (5) 用户、主机等创建

    1.创建新用户: 管理---> 用户--->创建用户 在右上角用户群组这里可以按下拉菜单,为某个组创建用户,默认是all 点击创建用户以后,出现如下图: 2.创建组 管理--->用户 ...

  8. zookeeper 随记

    ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务. zookeeper的几种模式: 1.单点模式 2.分布式集群模式,节点运行在多台机器 3.单点多实例 在这里只介绍单点多实例安装. ...

  9. [WEB安全]给BurpSuite设置非本地的网络代理

    目录 0x01 一般情况 0x02 移动端流量抓取 0x03 多重代理的情形 0x04 参考链接 在Web渗透测试过程中,BurpSuite是不可或缺的神器之一. BurpSuite的核心是代理Pro ...

  10. JS-七大查找算法

    顺序查找 二分查找 插值查找 斐波那契查找 树表查找 分块查找 哈希查找 查找定义:根据给定的某个值,在查找表中确定一个其关键字等于给定值的数据元素(或记录).查找算法分类:1)静态查找和动态查找:注 ...