166. Fraction to Recurring Decimal
来源:互联网 发布:日军轰炸重庆 知乎 编辑:程序博客网 时间:2024/05/17 19:21
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)".
Hint:
- No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
- Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
- Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
Because the ace rate is really low so I put some test cases below the solution.
Solution
public static String fractionToDecimal2(int numerator, int denominator) {if(numerator == 0){ return "0"; } StringBuilder sb = new StringBuilder(); sb.append(((numerator < 0) ^ (denominator < 0)) ? "-" : ""); long num = Math.abs((long)numerator);// consider integer overflow long den = Math.abs((long)denominator); sb.append(num / den); if(num % den == 0){ return sb.toString(); } sb.append("."); Map<String, Integer> map = new HashMap<String, Integer>(); long remain = num % den; map.put(remain + "", sb.length()); while(remain != 0){ remain = remain * 10; sb.append(remain / den); remain = remain % den; if(map.containsKey(remain + "")){ int index = map.get(remain + ""); sb.insert(index, "("); sb.append(")"); break; }else{ map.put(remain + "", sb.length()); } } return sb.toString(); }public static void main(String[] args) {System.out.println(fractionToDecimal2(1, 6));System.out.println(fractionToDecimal2(4, 7));System.out.println(fractionToDecimal2(-50, 8));System.out.println(fractionToDecimal2(-1, -2147483648));}
0 0
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- 166. Fraction to Recurring Decimal
- appium在真机上运行IOS实例要注意的几点:包括python和java运行log 和部分关键代码
- 阻塞式线程安全列表
- 删除文件
- iOS-OC-小知识整理
- 数据库中的事务理解
- 166. Fraction to Recurring Decimal
- AndroidUI布局----大白话版....
- [LeetCode][二叉树]Maximum Depth of Binary Tree
- 快速排序C++
- 欢迎使用CSDN-markdown编辑器
- 在ubuntu上搭建svn服务器
- SQL Server2008附加数据库之后显示为只读时解决方法
- 设计模式之1--五大原则
- 从2月14号开始,上传AppStore会碰到:Failed to locate or generate matching signing assets