Easy Java Solution


  • 0
    B

    The important thing is to consider all edge cases while thinking this problem through, including: negative integer, possible overflow, etc.

    Use HashMap to store the dividend and its associated index in the result while doing the division so that whenever a same dividend comes up, we know where the repeating fractional part begins.

    Please comment if you see something wrong or can be improved. Cheers!

    public class Solution {
        public String fractionToDecimal(int numerator, int denominator) {
            //require
            if(denominator==0)return "0";
            StringBuilder sb=new StringBuilder();
            Map<Long,Integer> map=new HashMap<>();
            //negative test 
            if((numerator>0&&denominator<0)||(numerator<0&&denominator>0))sb.append("-");
            long dividend=Math.abs((long)numerator),divisor=Math.abs((long)denominator);
            //invariant
            //count the integral part
            sb.append(dividend/divisor);
            //count the fractional part
            dividend=dividend%divisor*10;
            if(dividend==0)return sb.toString();
            else{
                sb.append(".");
                while(dividend!=0){
                    //repeating fractional
                    if(map.containsKey(dividend)){
                        sb.insert(map.get(dividend),"(");
                        sb.append(")");
                        break;
                    }
                    //record the dividend and its associated index
                    map.put(dividend,sb.length());
                    sb.append(dividend/divisor);
                    dividend=dividend%divisor*10;
                }
            }
            //ensure
            return sb.toString();
        }
    }
    

Log in to reply
 

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