47. 水仙花數
水仙花數的定義是,這個數等於他每一位數上的冪次之和 見維基百科的定義
比如一個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位數的水仙花數。
代碼區:
public class Solution {
/**
* username:softstarhhy
* @param n: The number of digits
* @return: All narcissistic numbers with n digits
*/
public List<Integer> getNarcissisticNumbers(int n) {
// write your code here
List list=new ArrayList<Integer>();
int start = (int)Math.pow(10, n-1);
int end = (int)Math.pow(10, n);
/* for(int s=0;s<n;s++)
{
n=(int)Math.pow(10,s+1);
if(s==(n-1))
{
n=n-1;
}
}*/
if(start == 1)
start = 0;
for(int j=start;j<=end;j++)
{
String sxhstr=String.valueOf(j);
char[] charsxh=sxhstr.toCharArray();
int[] numbers=new int[charsxh.length];
for(int k=0;k<numbers.length;k++)
{
numbers[k]=charsxh[k]-'0';
}
int len=numbers.length;
int current=0;
int sum=0;
for(int i=0;i<len;i++)
{
current=(int)Math.pow(numbers[i],len);
sum=sum+current;
if((j==sum)&&(i==(len-1)))
{
list.add(j);
}
}
}
return list;
}
}