Simple Java solution Using HashMap and StringBuilder


  • 3
    N
    public String fractionToDecimal(int numerator, int denominator) {
        long n=numerator;
    	long d=denominator;
    	if(n==0)return "0";
        int sign=1;
        if(numerator<0){sign=-sign;n=-n;}
        if(denominator<0){sign=-sign;d=-d;}   
        
        StringBuilder sb=new StringBuilder();
        if(sign==-1)sb.append("-");
        sb.append(n/d);
        n%=d;
        if(n==0)return sb.toString();
        sb.append(".");
        
        HashMap<Long,Integer>map=new HashMap();
        List<Long>list=new ArrayList();
        int index=0;
        while(n!=0&&!map.containsKey(n)){
            map.put(n,index++);
            n*=10;
            list.add(n/d);
            n%=d;
        }
        //Divide process finished
        if(n==0){ //No repeat
            for(int i=0;i<list.size();i++){
                sb.append(list.get(i));
            }
            return sb.toString();
        }else{ //Has repeat
            int startIndex=map.get(n);    
            for(int i=0;i<startIndex;i++){
                sb.append(list.get(i));
            }
            sb.append("(");
            for(int i=startIndex;i<list.size();i++){
                sb.append(list.get(i));
            }
            sb.append(")");
            return sb.toString();
        }
    }

Log in to reply
 

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