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:

1
2
3
4
5
6
7
class Solution:
    def isNarcissisticNumber(self, n):
        l = len(str(n))
        a = 0
        for i in str(n):
            a += int(i) ** l
        return a == n
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
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 tex_61ffe69666a905587cb99efbdef28320 Algorithms to Check Narcissistic Number algorithms c / c++ math python function. And compute the sum of powers by using the pow function.

1
2
3
4
5
6
7
8
9
10
11
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;
}
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) —

GD Star Rating
loading...
344 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

Leave a Reply