import java.util.ArrayList; import java.util.List; public class CircleDigitsInDivision { /** * 题目:求循环节,若整除则返回NULL,否则返回char*指向循环节。先写思路。函数原型:char*get_circle_digits(unsigned k,unsigned j) * 解答: 回想我们使用手算时如何发现循环节: * -如果除得的余数等于0,则说明整除; * -如果除得的余数不等于0,则将余数乘以10,继续相除; * -直到发现两次获得的余数相等,则找到了循环节。 * 以下程序用一个ArrayList来存储余数,当某次求得的余数在这个ArrayList里面已存在,则循环找到 */ public static void main(String[] args) { int dividend=1; for(int i=1;i<50;i++){ String str = circleDigits(dividend,i); if(str!=null){ System.out.println(dividend+"/"+i+"-"+str+"-"+(0.0+dividend)/i); } } } public static String circleDigits(int dividend, int divisor) { if (dividend < 0 || divisor <= 0) { return null; } if (dividend % divisor == 0) { return null; } List<Integer> quotientList = new ArrayList<Integer>();//store a/b List<Integer> leftList = new ArrayList<Integer>();//store a%b int left= dividend % divisor; while(!leftList.contains(left)){ leftList.add(left); left*=10; int quotient=left / divisor; quotientList.add(quotient); left%=divisor; if(left==0){ return null; } } int circleBegin=leftList.indexOf(left); quotientList = quotientList.subList(circleBegin,quotientList.size()); //transfer list [x,y,z] to "xyz" StringBuilder sb=new StringBuilder(); for(int i=0,len=quotientList.size();i<len;i++){ sb.append(quotientList.get(i)); } return sb.toString(); } }