Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public String fractionToDecimal(int numerator, int denominator) {
- // Edge case: numerator is 0
- if (numerator == 0) {
- return "0";
- }
- StringBuilder fraction = new StringBuilder();
- // If numerator and denominator have the different sign
- if (numerator < 0 ^ denominator < 0) {
- fraction.append("-");
- }
- // integral part
- long dividend = Math.abs(Long.valueOf(numerator));
- long divisor = Math.abs(Long.valueOf(denominator));
- fraction.append(String.valueOf(dividend / divisor));
- long remainder = dividend % divisor;
- if (remainder == 0) {
- return fraction.toString();
- }
- // fractional part
- fraction.append(".");
- Map<Long, Integer> map = new HashMap<>();
- while (remainder != 0) {
- if (map.containsKey(remainder)) {
- fraction.insert(map.get(remainder), "(");
- fraction.append(")");
- break;
- }
- map.put(remainder, fraction.length());
- remainder *= 10;
- fraction.append(String.valueOf(remainder / divisor));
- remainder %= divisor;
- }
- return fraction.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement