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 题目汇总

最新文章

  1. Centos6.5搭建java开发环境
  2. Selenium_模拟淘宝登录Demo
  3. SqlDataReader执行带输出参数存储过程 错误分析
  4. struts2中的addActionError 、addFieldError、addActionMessage的方法
  5. Andorid面试问题整理
  6. 树形dp求树的重心
  7. WebApi传递JSON参数
  8. 【Tips】Endnote导入IEEE Xplore文献方法《转载》
  9. [Cacti] memcache安装执行、cacti监控memcache实战
  10. js经典闭包
  11. javaScript 验证码 倒计时60秒
  12. 处理eclipse启动时报java.lang.IllegalStateException
  13. OO期末总结
  14. Winform 关闭按钮
  15. npm cnpm
  16. sql先分组,再算百分比
  17. 使用spring-boot-maven-plugin插件打包spring boot项目
  18. 007-Shell test 命令,[],[[]]
  19. VS和IE或者360兼容模式简单调试js方法
  20. java 流 文件 IO

热门文章

  1. 用于异步事件驱动的 P 语言 P Language
  2. python 单引号与双引号的转义
  3. bootstrap最简单的导航条
  4. div 水平垂直居中
  5. 01_第一次如何上传GitHub(转)Updates were rejected because the tip of your current branch is behind
  6. 验证账号密码是否为空 if格式
  7. 45 | 自增id用完怎么办?
  8. java上传文件夹文件
  9. NAS,IP SAN以及iSCSCI SAN存储的一些认识和理解
  10. CF891C Envy【最小生成树】