跳到正文

个人记录

【第三关 娱乐走迷宫】自恋数 TJ

yxShaw约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include <iostream>
using namespace std;

int main() {
    int a, b;
    cin >> a >> b;

    // 预处理0-9的1-8次幂(覆盖1到1e7的所有位数)
    // power[n][d]表示数字d的n次幂,n从1到8,d从0到9
    long long power[9][10] = {0};  // 使用long long防止溢出
    for (int n = 1; n <= 8; ++n) {
        for (int d = 0; d < 10; ++d) {
            long long res = 1;
            for (int i = 0; i < n; ++i) {
                res *= d;
            }
            power[n][d] = res;
        }
    }

    int count = 0;

    for (int x = a; x <= b; ++x) {
        // 计算x的位数n
        int n;
        if (x < 10) {
            n = 1;
        } else if (x < 100) {
            n = 2;
        } else if (x < 1000) {
            n = 3;
        } else if (x < 10000) {
            n = 4;
        } else if (x < 100000) {
            n = 5;
        } else if (x < 1000000) {
            n = 6;
        } else if (x < 10000000) {
            n = 7;
        } else {  // x == 10000000,8位数
            n = 8;
        }

        // 计算各位数字的n次幂之和
        int temp = x;
        long long total = 0;
        while (temp > 0) {
            int d = temp % 10;
            total += power[n][d];
            temp /= 10;
        }

        if (total == x) {
            count++;
        }
    }

    cout << count << endl;
    return 0;
}
原文