Fraction to Recurring Decimal
2015-09-27 11:14
260 查看
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.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
https://leetcode.com/discuss/23079/my-clean-java-solution
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
import java.util.HashMap; 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(); } public static void main(String[] args) { Solution solution = new Solution(); String res = solution.fractionToDecimal(1, 3); System.out.println(res); } }
https://leetcode.com/discuss/23079/my-clean-java-solution
相关文章推荐
- MySQL和Navicat使用总结
- Fragment详解
- 万能适配器的打造!
- 消除eclipse中php项目的错误提示
- 软件测试基础与基于生命周期的软件测试
- 给定一个二叉树和任意一个节点,求该该节点的下一层的第一个节点
- 函数式编程笔记
- Linux下挂在SD卡
- lua几个易与其他语言(特别C++)混淆的地方
- 素数环 nyoj (dfs)
- java面试题二十五 构造函数
- 深层复制与浅层复制
- Java核心技术第3章(4)
- 用反射封装HttpHandler,实现通过action方法名调用方法
- 更改nginx网站根目录
- 链表常用函数
- LAMP+DNS+nfs+Samba实现discuz论坛
- VIM+Ctags Linux源码阅读神器
- PPT制作教程:如何制作ppt
- HDU 5476 Explore Track of Point(平面几何)