# -*- coding: utf-8 -*-

# Copyright 2015 Shao Tian-Chen (Austin)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


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

__author__ = 'shaotch'

import unittest


class Solution:
    # @return a string
    def fractionToDecimal(self, numerator, denominator):
        if denominator == 0:
            return ""
        if numerator == 0:
            return "0"

        ret = ""
        m = {}

        if (numerator < 0) ^ (denominator < 0):
            ret += '-'

        numerator = int(abs(numerator))
        denominator = int(abs(denominator))
        ret += str(numerator / denominator)
        if numerator % denominator == 0:
            return ret

        ret += '.'
        r = numerator % denominator
        while r:
            if r in m:
                ret = ret[:m[r]] + '(' + ret[m[r]:] + ')'
                break
            m[r] = len(ret)
            r *= 10
            ret += str(r / denominator)
            r %= denominator
        return ret


class SolutionTest(unittest.TestCase):
    def testFractionToDecimal(self):
        solution = Solution()
        input_data = [(1, 2), (2, 1), (2, 3), (-50, 8)]
        expected = ["0.5", "2", "0.(6)", "-6.25"]
        actual = [solution.fractionToDecimal(n, d) for n, d in input_data]
        self.assertListEqual(expected, actual)
