Algorithms, Blockchain and Cloud

Algorithms to Check Narcissistic Number


Given an integer n, return whether it is equal to the sum of its own digits raised to the power of the number of digits.

Example 1
Input
n = 153
Output
True
Explanation
153 = 1 ** 3 + 5 ** 3 + 3 ** 3

Check Narcissistic Number in Python

The key part is to obtain the length of the number (e.g. the number of digits): We can either do this by converting it to a string, or iteratively divide by 10:

Converting a number to string, then compute the sum of powers. Once we convert the number into a string, we can easily iterate the digits:

class Solution:
    def isNarcissisticNumber(self, n):
        l = len(str(n))
        a = 0
        for i in str(n):
            a += int(i) ** l
        return a == n

And below is the log(N) method to compute the length of a number then compute the sum of powers:

class Solution:
    def isNarcissisticNumber(self, n):
        def getLen(n):
            if n == 0:
                return 1
            l = 0
            while n > 0:
                l += 1
                n //= 10
            return l
        l = getLen(n)
        a = 0
        for i in str(n):
            a += int(i) ** l
        return a == n

Check Narcissistic Number in C++

we can also get the length by using the function. And compute the sum of powers by using the pow function.

bool isNarcissisticNumber(int n) {
    using ll = long long;
    ll sum = 0;
    int len = ceil(log10(n+1));
    int m = n;
    while (m) {
        sum += pow(m%10, len);
        m /= 10;
    }
    return sum == n;
}

–EOF (The Ultimate Computing & Technology Blog) —

327 words
Last Post: Teaching Kids Programming - Algorithms of Greatest Common Divisor and Least Common Multiples
Next Post: Teaching Kids Programming - Compute the Average and Median

The Permanent URL is: Algorithms to Check Narcissistic Number (AMP Version)

Exit mobile version