通过余数判断是否是无限循环小数,我用set集合来判断。参考其他大佬的解法,用HashMap更好,value记录第几位小数,通过动态数组arraylist直接找出循环节。

import java.util.*;

public class Main {
    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        if(a % b == 0){
            System.out.println(a / b);
        }else{
            Set<Integer> set = new HashSet<>();
            ArrayList<Integer> arrayList = new ArrayList<>();
            arrayList.add(a / b);
            int p = a % b;
            boolean flag = false;
            while (p != 0) {
                if(!set.contains(p)){
                    set.add(p);
                    arrayList.add((p * 10) / b);
                    p = (p * 10) % b;
                }else{
                    flag = true;
                    break;
                }
            }
            if(flag){
                String res = a / b + ".";
                int q = a % b;
                while (q != p) {
                    res += (q * 10) / b;
                    q = (q * 10) % b;
                }
                res += "(";
                res += (q * 10) / b;
                q = (q * 10) % b;
                while (q != p) {
                    res += (q * 10) / b;
                    q = (q * 10) % b;
                }
                res += ")";
                System.out.println(res);
            }else{
                StringBuilder res = new StringBuilder(arrayList.get(0) + ".");
                for(int i = 1; i < arrayList.size(); i++){
                    res.append(arrayList.get(i));
                }
                System.out.println(res.toString());
            }
        }

    }
}