输出无限循环小数循环个数(java实现版本)

问题描述:

  输入两个整数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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值