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

【leetcode】Fraction to Recurring Decimal

时间:2015-01-18 20:58:51      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Fraction to Recurring Decimal

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

 

    0.16  
6 ) 1.00
    0 
    1 0       <-- Remainder=1, mark 1 as seen at position=0.
    - 6 
      40      <-- Remainder=4, mark 4 as seen at position=1.
    - 36 
       4      <-- Remainder=4 was seen before at position=1, so the fractional part which is 16 starts repeating at position=1 => 1(6).

如果发现余数曾经出现过,则说明开始循环了,利用一个hash表记录余数出现的位置即可
注意INT_MIN转换成正数会溢出,故需要先把数字先转为long long int
注意余数也要去long long int,因为-1,2147483648这种情况下,余数在计算乘以10的过程中会溢出
 
 1 class Solution {
 2 public:
 3     string fractionToDecimal(int numerator, int denominator) {
 4        
 5        
 6         string ans="";
 7         if(numerator==0) return "0";
 8        
 9         long long int n=numerator;
10         long long int d=denominator;
11         n=abs(n);
12         d=abs(d);
13        
14         if(numerator<0^denominator<0) ans.push_back(-);
15        
16         map<long long int,int> hash;
17        
18         ans+=to_string(n/d);
19         long long int rem=n%d;
20         if(rem!=0) ans.push_back(.);
21        
22         while(rem!=0)
23         {
24             if(hash.find(rem)!=hash.end())
25             {
26                 ans.insert(hash[rem],"(");
27                 ans.push_back());
28                 break;
29             }
30            
31             hash[rem]=ans.length();
32            
33             ans+=to_string(rem*10/d);
34             rem=(rem*10)%d;
35         }
36        
37         return ans;
38     }
39 };

 

【leetcode】Fraction to Recurring Decimal

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4232228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!