zoukankan      html  css  js  c++  java
  • 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");
    }
    

  • 相关阅读:
    【LeetCode】306. Additive Number
    【LeetCode】49. Group Anagrams
    【LeetCode】233. Number of Digit One
    【LeetCode】73. Set Matrix Zeroes
    【LeetCode】284. Peeking Iterator
    【LeetCode】241. Different Ways to Add Parentheses
    【LeetCode】289. Game of Life
    新版Java为什么要修改substring的实现
    计算机中整数加法满足结合律吗
    双色球中奖概率分析
  • 原文地址:https://www.cnblogs.com/Chen-Jr/p/11007307.html
Copyright © 2011-2022 走看看