Codeforces 900B (Java高精度或模拟)

题面:
B. Position in Fraction
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You have a fraction . You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point.

Input

The first contains three single positive integers a, b, c (1 ≤ a < b ≤ 105, 0 ≤ c ≤ 9).

Output

Print position of the first occurrence of digit c into the fraction. Positions are numbered from 1 after decimal point. It there is no such position, print -1.

Examples
Input
Copy
1 2 0
Output
Copy
2
Input
Copy
2 3 7
Output
Copy
-1
Note

The fraction in the first example has the following decimal notation: . The first zero stands on second position.

The fraction in the second example has the following decimal notation: . There is no digit 7 in decimal notation of the fraction. 

    题面描述:给你三个整数 a,b,c. 问a除以b所得到的浮点数中小数位内是否包含数字c。
    最开始拿到题目的时候,看到这是浮点数的处理,个人觉得如果采用double相除获取小数点后的位数可能会产生精度上的问题。因此就用了Java里面的BigDecimal进行高精度的处理。代码如下:
    
import java.util.*;
import java.math.*;
public class Main {
	public static void main(String[] args) {
		Scanner sca=new Scanner(System.in);
		BigDecimal res=BigDecimal.valueOf(1);
		BigDecimal a,b;
		a=sca.nextBigDecimal();
		b=sca.nextBigDecimal();
		int n;
		n=sca.nextInt();
		res=a.divide(b,100005,RoundingMode.HALF_UP);
		String str;
		str=res.toString();
		int index=str.indexOf('.');
		int flag=1;
		for(int i=index;i<str.length()-1;i++) {
			char tmp;
			tmp=str.charAt(i);
			if(tmp==(n+'0')) {
				System.out.println(i-1);
				flag=0;
				break;
			}
		}
		if(flag==1) System.out.println(-1);
	}
}

    最后看了各路大佬的代码,才发现这题大可采用int模拟除法的方法进行解决。具体就是每次把a的数扩大10倍,然后再整除b获取下一位的位数,再a%b消除这一位的影响。不断模拟即可。
       

    高精度就纯当熟悉Java了~~╮(╯▽╰)╭    

#include <bits/stdc++.h>
#define maxn 500
using namespace std;
int main()
{
    int a,b,c;
    cin>>a>>b>>c;
    bool flag=true;
    int ans=-1;
    for(int i=1;i<=maxn;i++){
        a*=10;
        if(a/b==c){
            cout<<i<<endl;
            flag=false;
            break;
        }
        a=a%b;
    }
    if(flag) puts("-1");
}

posted @ 2018-04-23 13:06  ChenJr  阅读(221)  评论(0编辑  收藏  举报