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:

    Input Outut

    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;
}

發佈了40 篇原創文章 · 獲贊 381 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章