IsNarcissistic

A Narcissistic Number (or Armstrong Number) is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).

Narcissistic Number (or Armstrong Number) is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).

For example, take 153 (3 digits), which is narcissistic:

    1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

and 1652 (4 digits), which isn’t:

    1^4 + 6^4 + 5^4 + 2^4 = 1 + 1296 + 625 + 16 = 1938

The Challenge:

Your code must return true or false (not ’true’ and ‘false’) depending upon whether the given number is a Narcissistic number in base 10.

This may be True and False in your language, e.g. PHP.

Error checking for text strings or other invalid inputs is not required, only valid positive non-zero integers will be passed into the function

image.png

We just use MATH.POW for start

    public static boolean isNarcissistic(int number) {  
        if(number < 0){  
            return false;  
        }        int temp = number;  
        int sum = 0;  
        int count = String.valueOf(temp).length();  
        while(temp != 0) {  
            sum += Math.pow(temp % 10, count);  
            temp = temp / 10;  
        }        boolean isNarcissistic = sum == number;  
        return isNarcissistic;  
    }}

Actually ,There are only few narcissistic numbers in the signed 32-bit with switch case, is easy to flow through all cases

public static boolean isNarcissistic(int number) {  
    switch (number) {  
        case 0:  
        case 1:  
        case 2:  
        case 3:  
        case 4:  
        case 5:  
        case 6:  
        case 7:  
        case 8:  
        case 9:  
        case 153:  
        case 370:  
        case 371:  
        case 407:  
        case 1_634:  
        case 8_208:  
        case 9_474:  
        case 54_748:  
        case 92_727:  
        case 93_084:  
        case 548_834:  
        case 1_741_725:  
        case 4_210_818:  
        case 9_800_817:  
        case 9_926_315:  
        case 24_678_050:  
        case 24_678_051:  
        case 88_593_477:  
        case 146_511_208:  
        case 472_335_975:  
        case 534_494_836:  
        case 912_985_153:  
            return true;  
        default:  
            return false;  
    }}
Last modified April 7, 2025: update codewar (7e82e67)