CF1277A Happy Birthday, Polycarp! 题解

· · 题解

思路

这道题 n 的范围是 1 \le n \le 10^9 ,但在这个范围内的完美的数个数并不多,共有 9 \times 9=81 个,应此我们可以直接考虑枚举出由 1~9 组成的完美的数。

代码:

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

const int N = 1e2 + 10;
int a[N] = {1, 11, 111, 1111, 11111, 111111, 1111111, 11111111, 111111111, 
            2, 22, 222, 2222, 22222, 222222, 2222222, 22222222, 222222222, 
            3, 33, 333, 3333, 33333, 333333, 3333333, 33333333, 333333333,
            4, 44, 444, 4444, 44444, 444444, 4444444, 44444444, 444444444,
            5, 55, 555, 5555, 55555, 555555, 5555555, 55555555, 555555555,
            6, 66, 666, 6666, 66666, 666666, 6666666, 66666666, 666666666,
            7, 77, 777, 7777, 77777, 777777, 7777777, 77777777, 777777777,
            8, 88, 888, 8888, 88888, 888888, 8888888, 88888888, 888888888,
            9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999};

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        int ans = 0;
        for (int i = 1; i <= 81; i++) {
            if (a[i] <= n) {
                ans++;
            }
        }
        cout << ans << "\n";
        ans = 0;
    }
    return 0;
}