5ms solution. Can someone suggest how can I improve this?


  • 0
    A
    public class Solution {
        public String fractionToDecimal(int numerator, int denominator) {
            if (numerator == 0){
                return "0";
            }
            boolean  flag = false;
            if ((numerator < 0 && denominator < 0) || (numerator >= 0 && denominator >= 0)){
                flag = false;
            }
            else {
                flag = true;
            }
            long absNum = Math.abs ((long)numerator);
            long absDen = Math.abs ((long)denominator);
            String res = (absNum/absDen) +"";
            long bal = (absNum % absDen);
            if (bal == 0){
                if (flag){
                    return "-"+res;
                }
                return res;
            }
            else {
                res += ".";
            }
            Map<Long,Integer> hs = new HashMap<Long,Integer>();
            long num = 0;
            int pos = 0;
            
            while (bal != 0){
                if (!hs.containsKey(bal)){
                    hs.put (bal,pos++);
                }
                else {
                    int i = 0;
                    while (res.charAt(i++) != '.');
                    int end = i + 1 + hs.get (bal);
                    res = res.substring (0,end-1)+"("+res.substring(end-1,res.length()) +")";
                    if (flag){
                        return "-"+res;
                    }
                    else {
                        return res;
                    }
                }
                num = Math.abs((bal * 10) / absDen);
                bal = Math.abs((bal * 10) % absDen);
                
                res += num;
            }
            if (flag){
                return "-"+res;
            }
            return res;
        }
    }

Log in to reply
 

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