算法竞赛入门-循环小数(Repeating Decimals)

1、题目

输入整数a(0<=a<=3000)和 b (1<=b<=3000),输出a/b的循环小数表示以及循环字节长度。例如a=5,b=43,小数表示为0.(116279069767441860465),循环字节长度为21。 

2、思路

第一步:先算出 a/b 的 商
第二步:算出 a%b 的余数
第三步:循环计算  (余数远远小于除数,所以需要将余数扩大10倍,然后再被除数相除,然后循环)

3、代码

package basic.第三章;

import java.util.Scanner;

/**
 * 循环小数(Repeating  Decimals)
 * 题目:
 * 输出a/b的循环小数表示以及循环节长度
 * Created by Administrator on 2018/4/12.
 * 

* 第一步:先算出 a/b 的 商 * 第二步:算出 a%b 的余数 * 第三步:循环计算 (余数远远小于除数,所以需要将余数扩大10倍,然后再被除数相除,然后循环) * * @author 春风吹又生 */ public class RepeatingDecimals { static int[] arr = new int[3000]; // 用来存储余数 static int[] tep = new int[3000]; // 用来存储被除数 public static void main(String[] args) { Scanner read = new Scanner(System.in); int a = read.nextInt(); int b = read.nextInt(); int x = a / b; int temp = a % b * 10; int index = 0; while (tep[temp] == 0) { // 如果被除数没有重复 int yu = temp / b; tep[temp] = 1; arr[index++] = yu; temp = temp % b * 10; } System.out.print(x+".("); for (int i = 0; i < index; i++) { System.out.print(arr[i]); } System.out.println(")"); System.out.println(index); } }

经提示,以上代码有问题,不能正确完成。经查看调试,没有考虑有一些数据时非循环的。解决方案是:在循环计算小数点的数据时,采用一个temp变量来存储当前位数,当循环结束也就是找到循环小节的时候,根据temp变量可以得到非循环的小数,也就是小于temp的之前的数为非循环小节。

package basic.第三章;

import java.util.Scanner;

/**
 * 循环小数(Repeating  Decimals)
 * 题目:
 * 输出a/b的循环小数表示以及循环节长度
 * Created by Administrator on 2018/4/12.
 * 

* 第一步:先算出 a/b 的 商 * 第二步:算出 a%b 的余数 * 第三步:循环计算 (余数远远小于除数,所以需要将余数扩大10倍,然后再被除数相除,然后循环) * * @author 春风吹又生 */ public class RepeatingDecimals { static int[] arr = new int[3000 + 5]; static int[] tep = new int[3000 + 5]; public static void main(String[] args) { Scanner read = new Scanner(System.in); int a = read.nextInt(); int b = read.nextInt(); // 得商 int x = a / b; // 得余数 int temp = a % b; // temp变量用于标记循环小数的开始, 在temp之前的都不是循环小数 // 得到剩余待除 a = a % b * 10; int index = 0; while (tep[temp] == 0) { // 如果当前的余数没有相同的 int yu = a / b; // 得商 arr[++index] = yu; // 存储该商 tep[temp] = index; // 存储余数的下标 temp = a % b; // 得余数 a = a % b * 10; // 得到剩余待除 } //arr[1]=1 arr[2]=6 //temp[1]= 1 temp[4]=2 //temp=4 index=2 System.out.print(x + "."); if (a == 0) {// 如果被整除 for (int i = 1; i < index; i++) System.out.print(arr[i]); System.out.println("(0)"); System.out.println(1); return; } // 如果没有整除 for (int i = 1; i < tep[temp]; i++) { // 在之前的不是循环小数 System.out.print(arr[i]); } System.out.print("("); for (int i = tep[temp]; i <= index && i <= tep[temp] + 100; i++) { System.out.print(arr[i]); } System.out.println(")"); System.out.println(index - tep[temp] + 1); } }

 

你可能感兴趣的:(Java,算法,算法竞赛入门)