public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        HashMap<Long,Integer> maps = new HashMap<>();//store divid number
        List<Long> number = new ArrayList<>();
        int index = 0;
        int beginIndex = -1;

        StringBuilder builder = new StringBuilder();
        if(denominator==0)
            return "";
        long num = numerator;
        long denum = denominator;
        if((num<0 && denum>0) || (num>0 && denum<0))
            builder.append('-');

        num = Math.abs(num);
        denum = Math.abs(denum);

        long val = num/denum;
        builder.append(String.valueOf(val));
        num = (num%denum)*10;

        while(num!=0){
            if(maps.containsKey(num)){//开始重复
                beginIndex = maps.get(num);
                break;
            }else{

                maps.put(num, index++);
                val = num/denum;
                num = (num%denum)*10;
                number.add(val);
            }
        }
        for(int i = 0;i<index;i++){
            if(i==0)
                builder.append('.');
            if(i==beginIndex){
                builder.append('(');
            }
            builder.append(number.get(i));
        }
        if(beginIndex!=-1)
            builder.append(')');

        return builder.toString();
    }
}

 

posted on 2018-10-21 21:02  Sempron2800+  阅读(121)  评论(0编辑  收藏  举报