本文共 877 字,大约阅读时间需要 2 分钟。
147.水仙花数
水仙花数的定义是,这个数等于他每一位数上的幂次之和
比如一个3位的十进制整数153就是一个水仙花数。因为 153 = 13 + 53 + 33。
而一个4位的十进制数1634也是一个水仙花数,因为 1634 = 14 + 64 + 34 + 44。
给出n,找到所有的n位十进制水仙花数。
样例
样例 1:
输入: 1
输出: [0,1,2,3,4,5,6,7,8,9]
样例 2:
输入: 2
输出: []
样例解释: 没有2位数的水仙花数。
注意事项
你可以认为n小于8。
public class Solution {
/**
* @param n: The number of digits
* @return: All narcissistic numbers with n digits
*/
public List<Integer> getNarcissisticNumbers(int n) {
// write your code here
List<Integer> integerList = new ArrayList<>();
if (n <= 0) return integerList;
int len = getSquare(10,n),m = len / 10,cur ,sum = 0;
int i, j;
if(m==1)m=0;
for (cur=0 ; m <len; m++) {
cur =m;
sum=0;
do {
i = (cur % 10);
cur = cur / 10;
sum = sum+getSquare(i,n);
} while (cur>0);
if (sum==m){
integerList.add(m);
}
}
return integerList;
}
public int getSquare(int n,int m){
int temp=n;
for (int i=1;i<m;i++){
temp=temp*n;
}
return temp;
}
}
转载地址:https://blog.csdn.net/xwdrhgr/article/details/116005203 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!