LintCode 147: Narcissistic Number (水仙花数)

  1. 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值