-
题目:
水仙花数的定义是,这个数等于他每一位数上的幂次之和 见维基百科的定义
比如一个3位的十进制整数
153
就是一个水仙花数。因为 153 = 13 + 53 + 33。而一个4位的十进制数
1634
也是一个水仙花数,因为 1634 = 14 + 64 + 34 + 44。给出
n
,找到所有的n位十进制水仙花数。
-
首先了解一下math.pow()函数
pow() 函数用来求 x 的 y 次幂次方,其原型为:double pow(double x, double y);设返回值为 ret,则 ret = xy。
-
题目解答
package lintcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Solution_147 {
public List<Integer> getNarcissisticNumbers(int n) {
int limit_latter = (int)Math.pow(10, n);//10^n
int limit_former = (int)Math.pow(10, n - 1);//10^(n-1)
int[] digit = new int[n];
int count;
int dup1 , dup2;
List<Integer> result = new ArrayList<>();
if(n == 1)
limit_former = 0;//添加0的情况
int num = limit_former;
for (; num < limit_latter; num++) //limit_former开始
{
dup1 = num;
dup2 = num;
count = 1;
//个位:digit[0];十位:digit[1];百位:digit[2];千位:digit[3];...
while(count<n+1) //1->n
{
digit[count-1] = dup1 % 10;// 求各个位,并保存在digit[](0->n-1)中
dup1 /= 10;
count++;
}
for (int m = 0; m < n; m++)
{
dup2 -= Math.pow(digit[m], n);//(digit[m])^n;判断水仙花数(减到0为止)
}
if (dup2 == 0)
{
result.add(num);
}
}
return result;
}
public static void main(String[] args) {
Solution_147 solution = new Solution_147();
Scanner s=new Scanner(System.in);
int n;
n=s.nextInt();
System.out.println(solution.getNarcissisticNumbers(n));
}
}
结果:
参考链接:https://blog.csdn.net/sjpz0124/article/details/45191299,https://www.jianshu.com/p/0591b8592c23