A very simple 0ms C++ solution


  • 1
    T

    Code first :)

    class Solution {
    public:
      string fractionToDecimal(int numerator, int denominator) {
        bool s = ((numerator ^ denominator) >> 31 & 0b1) == 1;
        if (numerator == 0 || denominator == 0) {
          s = false;
        }
        long _numerator = abs(static_cast<long>(numerator)), _denominator = abs(static_cast<long>(denominator));
        string res = to_string(_numerator / _denominator);
        if (_numerator % _denominator == 0) {
          goto end;
        } else {
          res.push_back('.');
        }
        res += fraction(_numerator % _denominator, _denominator);
        end:
        if (s) {
          res.insert(0, 1, '-');
        }
        return res;
      }
    
    private:
      string fraction(long numerator, long denominator) {
        unordered_map<long, int> hash;
        string res;
        long a = numerator, b = denominator;
        int cur = 0;
        while (a) {
          if (hash.count(a) != 0) {
            res.insert(hash[a], 1, '(');
            res.push_back(')');
            break;
          }
          hash[a] = cur++;
          a *= 10;
          res.push_back('0' + a / b);
          a %= b;
        }
        return res;
      }
    };
    

    The key is to imitate the decimal division by hand, as the function fraction(:) shows. I use hash to record all numbers appeared and their index. For each iteration, we check whether the number appeared before, if it does, then we can conclude that the decimal part is circulate decimal, and we need to insert the left parentheses to the position of it first appears, and insert the right one to the end.

    Besides, we need to notice some edge cases. The first one is the number -2147483648, because the abs(-2147483648) exceeds the range of an integer; therefore, we need to use long to store the value. The second is the sign of the result. 0 * -1 = 0.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.