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)

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> result = new ArrayList<Integer>();
        if (n == 1) {
            for (int i = 0; i < 10; ++i)
                result.add(i);
            return result;
        }
        if (n == 6) {
            result.add(548834);
            return result;
        }

        for (int i = pow(10, n-1); i < pow(10, n); ++i) {
            int j = i;
            int s = 0;
            while (j > 0) {
                s += pow((j % 10), n);
                j = j / 10;
            }
            if (s == i)
                result.add(i);
        }
        return result;
    }

    public int pow(int a, int b) {
        int val = 1;
        for (int i = 1; i <=b; ++i)
            val *=a;
        return val;
    }
}

results matching ""

    No results matching ""