- Narcissistic Number
中文English
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
Example 1:
Input: 1
Output: [0,1,2,3,4,5,6,7,8,9]
Example 2:
Input: 2
Output: []
Explanation: There is no Narcissistic Number with 2 digits.
Notice
You may assume n is smaller than 8.
解法1:先预处理。
代码如下:
class Solution {
public:
/**
* @param n: The number of digits
* @return: All narcissistic numbers with n digits
*/
vector<int> getNarcissisticNumbers(int n) {
if (n == 0) return vector<int>();
vector<int> results;
vector<int> powers(10, 0);
for (int i = 1; i < 10; ++i) {
powers[i] = pow(i, n);
}
int upperLimit = pow(10, n) - 1;
int lowerLimit = (n == 1) ? 0 : pow(10, n - 1);
for (int num = lowerLimit; num <= upperLimit; ++num) {
vector<int> digits(n, 0);
long long powSum = 0;
int saveNum = num;
for (int i = 0; i < n; ++i) {
digits[i] = saveNum % 10;
saveNum /= 10;
powSum += powers[digits[i]];
}
if (num == powSum) results.push_back(num);
}
return results;
}
};