码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Fraction to Recurring Decimal

时间:2014-12-22 22:46:16      阅读:197      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!