题:
-
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 86
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;
}