求一个3位是否为水仙花数

本文介绍了一种使用C++编程语言来判断三位数是否为水仙花数的方法,并提供了完整的代码实现。水仙花数是指一个三位数,其各个位上的数字立方和等于该数本身。文中还提供了一个获取所有三位水仙花数的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

求一个3位是否为水仙花数

水仙花数指一个数上各位上的数的立次方后的和,等于原来这个数
例如 371 = 33+73+13= 1 + 343 + 27

结果

All the narc nums:
153
370
371
407
Begin test
371
The num '371’IS Narc!!
443
The num '443’is NOT Narc!!

代码

#include <iostream>
#include <sstream>
#include <vector>

bool IsNarcNum(int num, bool debug= false) {
    if (num >= 1000 || num < 100)
        return false;

    std::stringstream strstr;
    int t = 0;
    int cur_n = num;
    const int count = 3;
    for (int i = 0; i < count; ++i) {
        int n = cur_n % 10;
        cur_n /= 10;
        int one_n = n * n * n;
        t += one_n;
        if (debug) {
            strstr << one_n;
            if (i < count - 1)
                strstr << " + ";
        }
    }
    if (debug) {
        strstr << " = " << t;
        std::cout << strstr.str() << std::endl;
    }
    return num == t;
}

void GetAllNarcNum(std::vector<int>& nums) {
    std::cout << "All the narc nums:" << std::endl;
    for (int i = 100; i < 999; ++i) {
        if (IsNarcNum(i)) {
            nums.push_back(i);
            std::cout << i << std::endl;
        }
    }
}


int main()
{
    std::vector<int> nums;
    GetAllNarcNum(nums);
    std::cout << "Begin test\n";
    while (true) {
        int check_num = 0;
        std::cin >> check_num;
        if (check_num < 0)
            break;
        bool res = IsNarcNum(check_num);
        std::cout << "The num \'" << check_num << "\'" << (res ? "IS " : "is NOT ") << "Narc!!" << std::endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值