題目描述:
統計一下 aaa ⋯ aaa * b (a有n個)的結果裏面有多少個數字d,a,b,d均爲一位數。
樣例解釋:
3333333333*3=9999999999,裏面有10個9。
Input
多組測試數據。
第一行有一個整數T,表示測試數據的數目。(1≤T≤5000)
接下來有T行,每一行表示一組測試數據,有4個整數a,b,d,n。 (1≤a,b≤9,0≤d≤9,1≤n≤10^9)
Output
對於每一組數據,輸出一個整數佔一行,表示答案。
Input示例
2
3 3 9 10
3 3 0 10
Output示例
10
0
解題思路:
本題可以用豎式來求解:假設 a*b = ef,則原問題等價於:
ef
+ ef
+ ef
......
所以問題的關鍵在於處理條件判斷的方式,稍有不慎就WA了。
第一種思路:以結果可能位數來判斷:
#include <cstdio>
using namespace std;
int main(){
int t;
scanf("%d", &t);
while(t--){
int a, b, d, n;
scanf("%d%d%d%d", &a, &b, &d, &n);
int left, right, sumLeft, sumRight;
right = a * b % 10;
left = a * b / 10;
sumLeft = (left + right) / 10;
sumRight = (left + right) % 10;
int res = 0;
if(left == 0){
if(right == d)
printf("%d\n", n);
else
printf("0\n");
}
else{
if(right == d)
res++;
if(n == 1){
if(left == d)
res++;
}
else{
if(sumRight == d)
res++;
if(sumRight+sumLeft == d)
res += n-2;
if(left+sumLeft == d)
res++;
}
printf("%d\n", res);
}
}
return 0;
}
另一種做法,個人感覺更加容易理解,思路更加清晰:
#include <cstdio>
using namespace std;
int main(){
int t;
scanf("%d", &t);
while(t--){
int a, b, d, n;
scanf("%d%d%d%d", &a, &b, &d, &n);
int res = 0, left, right;
right = a * b % 10;
left = a * b / 10;
if(right == d)
res++;
if(n == 1){
if(left != 0 && left == d)
res++;
}
else if(n == 2){
//這裏的處理也可以參考n > 3時的處理
if((left + right) % 10 == d)
res++;
if((left + right) / 10 + left == d && d != 0)
res++;
}
else{
int tmp = (a * 100 + a * 10 + a) * b;
if(tmp >= 1000 && tmp / 1000 == d)
res++;
tmp = tmp % 1000;
if(tmp / 100 == d)
res += n - 2;
tmp = tmp % 100;
if(tmp / 10 == d)
res++;
}
printf("%d\n", res);
}
return 0;
}