题目
求一个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;
}
}