51nod 1770 数数字

题目描述:
统计一下 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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章