Java solution, using map


  • 0
    M
    public class Solution {
        public String fractionToDecimal(int numerator, int denominator) {
            if(denominator==0) return null;
            if(numerator==0) return "0";
            StringBuilder sb = new StringBuilder();
            // sign
            String sign = (numerator>0)^(denominator>0) ? "-" : "";
            sb.append(sign);
            // Integer.MIN_VALUE overflow
            long num = Math.abs((long)numerator);
            long den = Math.abs((long)denominator);
            //Integer part
            sb.append(num/den);
            num = num % den;
            // no fraction part
            if(num == 0) 
                return sb.toString();
            // Fraction part
            sb.append(".");
            Map<Long, Integer> map = new HashMap<>();
            map.put(num, sb.length());
            while(num != 0){
                num *= 10; // *10 every time 
                sb.append(num/den);
                num = num%den;
                if( map.containsKey(num) ){
                    sb.insert(map.get(num), "(");
                    sb.append(")");
                    break;
                } else {
                    map.put(num, sb.length());
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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