首页 > 其他 > 详细

LeetCode Fraction to Recurring Decimal

时间:2014-12-22 22:45:23      阅读:314      评论:0      收藏:0      [点我收藏+]

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)".

 

Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.

 1 public class Solution {
 2     public String fractionToDecimal(int numerator, int denominator) {
 3         if (numerator==0) {
 4             return "0";
 5         }
 6         String result="";
 7         if (numerator<0 ^ denominator<0) {
 8             result+="-";
 9         }
10         long n=numerator;
11         long d=denominator;
12         n=Math.abs(n);
13         d=Math.abs(d);
14         long r=n%d;
15         result+=n/d;
16         if (r==0) {
17             return result;
18         }else {
19             result+=".";
20         }
21         HashMap<Long, Integer> map=new HashMap<>();
22         while (r>0) {
23             if (map.containsKey(r)) {
24 
25                 result=result.substring(0, map.get(r))+"("+result.substring(map.get(r))+")";
26                 return result;
27             }else {
28                 map.put(r, result.length());
29                 r*=10;
30                 result+=r/d;
31                 r=r%d;    
32             }
33         }
34         return result;
35     }
36 }

 

LeetCode Fraction to Recurring Decimal

原文:http://www.cnblogs.com/birdhack/p/4179114.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!