leetcode——166—— 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)".

分析如下:

对于可以整除的,和对于不可以整除但是算出来的小数不是循环小数的,都可以直接计算结果转化为字符串。
比较麻烦的是循环节的小数。为了找到循环节,可以用hashtable保存每一步余数,如果当前余数和之前某个余数相同,则重复之间的这段发生循环。

这里的我踩过的坑是,为什么hashtable保存的是每次计算的余数,而不是每次计算的商呢?因为小数部分有循环节部分,还有循环节之前的不规律的部分,如果保存商,则可能会把循环节之前的部分错误计算成循环节部分。

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        long long l_numerator = numerator;
        long long l_denominator = denominator;
        long long rest = 0;
        
        string result = "";
        unordered_map<long long , int> u_map;
        bool is_positive = true;
        if (l_denominator == 0) return result;
        if (l_numerator == 0) return "0";
        if (l_numerator == INT_MIN && l_denominator == -1) return "2147483648";
        if (l_numerator < 0) {
            is_positive = 1 - is_positive;
            l_numerator = - l_numerator;
        }
        if (l_denominator < 0) {
            is_positive = 1 - is_positive;
            l_denominator = - l_denominator;
        }
        if (l_numerator % l_denominator == 0) {
            result = to_string(l_numerator/l_denominator);
        } else {
            result = to_string(l_numerator / l_denominator) + '.';
        }
        
        rest = l_numerator % l_denominator;
        int index = result.length(); // starting point
        while (rest != 0 && u_map.find(rest) == u_map.end()) {
            u_map[rest] = index;
            rest *= 10;
           
            result += to_string(rest / l_denominator);
            rest = rest % l_denominator;
            index++;
        }
        if (rest != 0) {
            result.insert(u_map[rest], 1, '(');
            result.insert(result.length(), 1, ')');
        }
        if (is_positive)
            return result;
        else
            return "-" + result;
    }
};

你可能感兴趣的:(LeetCode,算法题)