-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path0147. Narcissitic Number.java
More file actions
39 lines (37 loc) · 947 Bytes
/
0147. Narcissitic Number.java
File metadata and controls
39 lines (37 loc) · 947 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class Solution {
/**
* @param n: The number of digits
* @return: All narcissistic numbers with n digits
*/
public List<Integer> getNarcissisticNumbers(int n) {
int min = pow(10, n - 1);
int max = min * 10;
List<Integer> result = new ArrayList<>();
if(n == 1){
min = 0;
}
for(int i = min; i < max; i++){
if(narcissistic(i)){
result.add(i);
}
}
return result;
}
public boolean narcissistic(int num){
int n = num;
int length = (n + "").length();
int sum = 0;
while(n > 0){
sum += pow(n % 10, length);
n /= 10;
}
return sum == num;
}
public int pow(int base, int power){
int result = base;
for(int i = 1; i < power; i++){
result *= base;
}
return result;
}
}