问题描述:
输入两个整数a、b,进行a/b运算。如果能除尽就直接输出结果。如果是无限循环小数就是输出循环个数,比如:结果是0.0000131313…….就输出2,结果是0.571425571425571425…….就输出6。
解题思路:
1.整除很好判断,只要第一次余数是0就可以啦。直接输出结果
2.判断是否能除尽,只要除后余数不为零就用余数一直除知道为零为止,输出结果。(和第一步有些重复)
3.无限循环小数情况,怎么判断是否为无限循环小数,只要余数比除数小就扩大十倍直到比余数大为止,再得到余数。重复操作直到得到的余数之前出现过可以判定是无限循环小数。
翠花上代码:
package cn.wzq.sword_finger_offer;
import java.util.HashMap;
import java.util.Map;
public class WuxianXunhuanXiaoshu {
public double display(int a, int b) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();//记录余数个数的数据结构
boolean isLoop = true;
double count = 0d;
int remainder = a % b;
int mark = 0;
//获取余数直到余数为零,或者出现余数相等判定为无限循环小数
while (isLoop) {
if (remainder == 0) {
count = (double) a / (double) b;
return count;
} else if (!map.containsKey(remainder)) {
map.put(remainder, mark);
mark++;
} else {
count = mark - map.get(remainder);
return count;
}
while (remainder < b) {
remainder = remainder * 10;
}
remainder %= b;
}
return count;
}
public static void main(String[] arg) {
WuxianXunhuanXiaoshu w = new WuxianXunhuanXiaoshu();
double count = w.display(1, 2);
System.out.println(count);
}
}