Wednesday, February 3, 2016

Narcissistic Number

Narcissistic Number

Narcissistic Number is a number that is the sum of its own digits each raised to the power of the number of digits. See wiki
For example the 3-digit decimal number 153 is a narcissistic number because 153 = 13 + 53 + 33.
And the 4-digit decimal number 1634 is a narcissistic number because 1634 = 14 + 64 + 34 + 44.
Given n, return all narcissistic numbers with n digits.

Example
Given 1, return [0,1,2,3,4,5,6,7,8,9].
Given 2, return [].
Note
You may assume n is smaller than 8.


 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
class Solution {
    /*
     * @param n: The number of digits. 
     * @return: All narcissistic numbers with n digits.
     */
    public ArrayList<Integer> getNarcissisticNumbers(int n) {
        // write your code here
        
        ArrayList<Integer> list = new ArrayList<Integer>();
        
        int start = 0;
        if (n > 1) {
            start = (int) Math.pow(10, n - 1);
        }
        int end = (int) Math.pow(10, n);
        
        for (int i = start; i < end; i++) {
            int num = i;
            int sum = 0;
            while (num != 0) {
                int digit = num % 10;
                sum += (int) Math.pow(digit, n);
                num = num / 10;
            }
            if (sum == i) {
                list.add(i);
            }
        }
        
        return list;
        
    }
}