Last updated on October 5th, 2024 at 04:27 pm
Here, We see Fraction to Recurring Decimal LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Hash Table, Math
Companies
Level of Question
Medium
Fraction to Recurring Decimal LeetCode Solution
Table of Contents
Problem Statement
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.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104 for all the given inputs.
Example 1:
Input: numerator = 1, denominator = 2
Output: “0.5”
Example 2:
Input: numerator = 2, denominator = 1
Output: “2”
Example 3:
Input: numerator = 4, denominator = 333
Output: “0.(012)”
1. Fraction to Recurring Decimal Leetcode Solution C++
class Solution { public: string fractionToDecimal(int numerator, int denominator) { if(!numerator) return "0"; string ans = ""; if (numerator > 0 ^ denominator > 0) ans += '-'; long num = labs(numerator), den = labs(denominator); long q = num / den; long r = num % den; ans += to_string(q); if(r == 0) return ans; ans += '.'; unordered_map<long, int> mp; while(r != 0){ if(mp.find(r) != mp.end()){ int pos = mp[r]; ans.insert(pos, "("); ans += ')'; break; } else{ mp[r] = ans.length(); r *= 10; q = r / den; r = r % den; ans += to_string(q); } } return ans; } };
2. Fraction to Recurring Decimal Leetcode Solution Java
class Solution { public String fractionToDecimal(int numerator, int denominator) { boolean isNegative = (numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0) ? true : false; long numeratorL = Math.abs((long) numerator); long denominatorL = Math.abs((long) denominator); Map<Long, Integer> previousRemains = new HashMap<Long, Integer>(); StringBuilder sb = new StringBuilder(); long quotian = numeratorL / denominatorL; sb.append(quotian); numeratorL %= denominatorL; if (numeratorL != 0) { sb.append("."); } int quotianIndex = 0; while (numeratorL != 0) { numeratorL *= 10; quotian = Math.abs(numeratorL / denominatorL); if (!previousRemains.containsKey(numeratorL)) { sb.append(quotian); previousRemains.put(numeratorL, quotianIndex++); } else { int firstIndex = 1 + previousRemains.get(numeratorL) + sb.indexOf("."); sb.insert(firstIndex, '('); sb.append(")"); break; } numeratorL %= denominatorL; } if (isNegative) { sb.insert(0, "-"); } return sb.toString(); } }
3. Fraction to Recurring Decimal Leetcode Solution JavaScript
var fractionToDecimal = function(numerator, denominator) { if(!numerator) return '0'; let str = ''; if(Math.sign(numerator) !== Math.sign(denominator)) str += '-'; const numer = Math.abs(numerator) const denom = Math.abs(denominator) str += Math.floor(numer/denom); let rem = numer%denom; if(!rem) return str; str += '.' const map = new Map(); while(rem !== 0) { map.set(rem, str.length); rem *= 10; str += Math.floor(rem/denom); rem %= denom if(map.has(rem)) { const idx = map.get(rem); return str.slice(0, idx) + `(${str.slice(idx)})`; } } return str; };
4. Fraction to Recurring Decimal Leetcode Solution Python
class Solution(object): def fractionToDecimal(self, numerator, denominator): n, remainder = divmod(abs(numerator), abs(denominator)) sign = '-' if numerator*denominator < 0 else '' result = [sign+str(n), '.'] stack = [] while remainder not in stack: stack.append(remainder) n, remainder = divmod(remainder*10, abs(denominator)) result.append(str(n)) idx = stack.index(remainder) result.insert(idx+2, '(') result.append(')') return ''.join(result).replace('(0)', '').rstrip('.')