UVA-1225 Digit Counting

来源:互联网 发布:qq美化主题软件 编辑:程序博客网 时间:2024/06/11 05:12

UVA-1225 Digit Counting

题目大意:给定一个数 n,求从 1 到 n 所有数中 0 ~ 9 有多少个。

Sample Input

2
3
13

Sample Output

0 1 1 1 0 0 0 0 0 0
1 6 2 2 1 1 1 1 1 1

方法一

解题思路:将 n 之前所有数连接成一个字符串,对字符串每一个进行判断。

#include <iostream>#include <stdlib.h>#include<string.h>using namespace std;int main() {    int m;    cin >> m;    while (m--) {        int i, j, t, q;        int r[15] = { 0 };        cin >> q;        char sum[100000] = "";        for (i = t = 0; i < q; i++) {            char tem[20];            t++;            sprintf(tem, "%d", t);            strcat(sum, tem);        }        for (i = 0; sum[i] != '\0'; i++) {            for (j = 0; j < 10; j++) {                if (sum[i] == j + '0')                    r[j]++;            }        }        for (j = 0; j < 10; j++) {            if(j==9)                cout << r[j];            else                cout << r[j]<< ' ';        }        cout << endl;    }}

方法二

解题思路:将大于 9 的数进行 循环取余 直到不再大于 9

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <cstring>using namespace std;int main(){    int a[15];    int t, n;    cin >> t;    while (t--)    {        memset(a, 0, sizeof(a));  //初始化        cin >> n;        for (int i = 1; i <= n; i++)        {            int t = i;            while (t)            {                int num = t % 10;                a[num]++;                t /= 10;            }        }        for (int i = 0; i<10; i++)  //输出        {            if (i)                cout << " ";            cout << a[i];        }        cout << endl;    }    return 0;}
0 0
原创粉丝点击