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 = 1^3 + 5^3 + 3^3.

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

Given n, return all narcissistic numbers with n digits.

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

分析:

只想到了这种比较笨的办法,并不知道数学上怎么优化这个过程

解法:

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> res = new ArrayList<Integer>();
        if (n < 1) {
            return res;
        }

        if (n == 1) {
            for (int i = 0; i <= 9; i++) {
                res.add(i);
            }
            return res;
        }

        for (int i = (int) Math.pow(10, n-1); i < (int) Math.pow(10, n); i++) {
            int rhs = 0;
            int num = i;
            while (num > 0) {
                int temp = num % 10;
                num /= 10;
                rhs += Math.pow(temp, n);
                if (rhs > i) {
                    break;
                }
            }
            if (rhs == i) {
                res.add(rhs);
            }
        }
        return res;
    }
};

results matching ""

    No results matching ""