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 number153is a narcissistic number because 153 = 1^3+ 5^3+ 3^3.

And the 4-digit decimal number1634is a narcissistic number because 1634 = 1^4+ 6^4+ 3^4+ 4^4.

Givenn, return all narcissistic numbers with n digits.

Example

Given1, return[0,1,2,3,4,5,6,7,8,9].

Given2, return[].

Notice

You may assume n is smaller than 8.

Analysis

Might be better to implement custom power function, since Math.pow() is returning double type.

Solution

public class Solution {
    /**
     * @param n: The number of digits
     * @return: All narcissistic numbers with n digits
     */
    public List<Integer> getNarcissisticNumbers(int n) {
        List<Integer> ans = new ArrayList();
        if (n == 0) return ans;

        int upperLimit = 1;
        int lowerLimit = 1;

        for (int i = 0; i < n; i++) {
            upperLimit *= 10;
        }
        if (n == 1) {
            lowerLimit = 0;
        } else {
            lowerLimit = 1;
            for (int i = 0; i < n - 1; i++) {
                lowerLimit *= 10;
            }
        }

        double sum = 0.0;
        for (int i = lowerLimit; i < upperLimit; i++) {
            int k = i;
            sum = 0.0; 
            while (k > 0) {
                sum = sum + Math.pow(k % 10, n);
                k = k / 10;
            }
            if (sum == (double) i) {
                ans.add(i);
            }
        }
        return ans;
    }
}

Jiuzhang's Solution (Using custom pow() function)

Last updated

Was this helpful?