[LeetCode]Fraction to Recurring Decimal

题目描述:

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

 

解题思路:

1. 要找出循环小数的序列,就需要找出相同的余数,则2个相同余数间计算出的小数就是循环小数;

2. 因为需要在循环数列之间插入括号,所以要使用hash表记录出现各余数时对应结果中的位置。

3. 该题目的数据比较大,使用int类型不够,需要使用int64_t类型。

 

解题代码:

class Solution {
public:
    string fractionToDecimal(int64_t numerator, int64_t denominator) {
        string result = "";
        if(numerator * denominator < 0)
        {
            result += '-';
        }
        
        int64_t num = abs(numerator), den = abs(denominator);
        
        result += to_string(num / den);
        
        if(num % den == 0)
        {
            return result;
        }
        else 
        {
            result += '.';
        }
        
        int64_t rem = num % den;
        map<int, int> rem_map;
        while(rem != 0)
        {
            if(rem_map[rem] > 0)
            {
                result.insert(rem_map[rem], 1, '(');
                result += ')';
                break;
            }
            
            rem_map[rem] = result.size();
            rem *= 10;
            result += to_string(rem / den);
            rem %= den;
        }
        
        return result;
    }
};
posted @ 2015-03-19 17:55  香菜小语  阅读(143)  评论(0编辑  收藏  举报