Yahoo! Hack Beijing Challenge----Question 1的c++解

题:

  • Given a rational number expressed as A/B where A and B are integers, find the position of Mth occurrence of digit D (0-9) after decimal point. For example 3/7 = 0.4285714285... (A=3, B=7), so the 2nd (M=2) 4 (D=4) is the 7th digit after decimal point.

    Limits:

    • 0 < A, B, M < 2 x 108

    • 0 <= D <= 9

    Input:

    The first line of the input gives the number of test cases, N. N test cases follow. Each test case consists of one line containing 4 numbers, A, B, M and D separated by spaces.

    Output:

    Each line contains the position (starting from 1) of the specified digit D. Output “0” if it is impossible to find the digit.

    Sample:

    InputOutut

    7
    3 7 1 1
    3 7 2 2
    3 7 3 6
    5 11 2 3
    5 11 3 7
    20 193 20 6
    200000 19893 50 8

    6
    8
    0
    0
    0
    191
    470

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int firstNum=0;
    bool isFirst=true;
	int a,b,m,d;
	int tem=0;
	int count=0,i,length;
	int position=0,times=0;
	string result="";
	char c='x';
	cin>>a;
	cin>>b;
	cin>>m;
	cin>>d;
	if(a/b!=0){
	    a=a%b;
	}
	int num=0;
	while(true)
	{

	    tem=0;
		while(a/b == 0){
		    num++;
			a *= 10;
			tem++;
			if(tem>1){
			    c='0';
			    result += c;
			}
		}
		if(isFirst){
		    firstNum=a;
		    c = a/b + 48;
		    result += c; //当前商数转为char后加入到结果集
            a = a%b;
            isFirst=false;
		}
		else{
		    c = a/b + 48;
            if(firstNum==a) //小数是否开始循环只需判断当前‘可除’的被除数是否跟第一个可除被除数相等
                break;
            result += c;
            a = a%b;
		}
	}
	d+=48;
	length=result.length();
	times=0;
	bool isContain=false;
	for(count=0;count<m;  ){
	    times++;
	    for(i=0;i<length;i++){
            if(d==result[i]){
                count++;
                isContain=true;
            }
            if(count==m)
                break;
	    }
	    if(!isContain){ //单次扫描结果集后仍无此数即无解
	        break;
	    }
	}
	if(!isContain){
	    position=0;
	    cout<<position<<endl;
	    return 0;
    }
	times--;
	position=times*length+i+1;
	cout<<position<<endl;
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值