250. 水仙花数1

题目描述

水仙花数是指一个N位正整数(N>=3),它的每个位上的数字的N次幂之和等于它本身。
例如:
153 = 1^3 + 5^3+ 3^3.

1634 = 1^4 + 6^4 + 3^4 + 4^4.

本题要求编写程序,计算所有N位水仙花数。

解答要求时间限制:2000ms, 内存限制:100MB
输入

输入的测试数据只有一行, 一个数字 N(输入数据保证 N >= 3 并且 N < 8)表示要求输出的水仙花数的位数.

输出

每组测试数据输出包括很多行。首先按照从小到大的顺序输出满足要求的数, 每个数一行;最后输出一个整数, 代表满足要求的数的个数.

样例

输入样例 1 复制

3

输出样例 1

153
370
371
407
4
思路:暴力可做
代码:
// we have defined the necessary header files here for this problem.
// If additional header files are needed in your program, please import here.
#include<iostream>
using namespace std;
int mathPow(int a, int b) {
    int res = 1;
    for (int i = 0; i < b; i++) {
        res *= a;
    }
    return res;
}
int judge(int N,int num)
{
    int b,k;
    int ori = num;
    int sum = 0;
    while(num>0)
    {
        b = num%10;
        num /= 10;
        sum+=mathPow(b,N);
    }
    if(sum == ori)
    {
        return 1;
    }
    else{
        return 0;
    }   
}
int main()
{  
  // please define the C++ input here. For example: int a,b; cin>>a>>b;;  
  // please finish the function body here.  
  // please define the C++ output here. For example:cout<<____<<endl; 
  int N;
  cin>>N;
  int low = mathPow(10,N-1);
  int high = mathPow(10,N);
  int cnt = 0;
  for(int i =low;i<high;i++)
  {
      if(judge(N,i) == 1)
      {
         cnt++;
         cout<<i<<endl;
      }
  }
   cout<<cnt<<endl;
    return 0;
}
以大多数人努力程度之低,根本轮不到去拼天赋~
原文地址:https://www.cnblogs.com/gcter/p/15471600.html