Algo Breakdown — Narcissistic Number

Hey all, I’m back at it with another algorithm breakdown. This is a format I’ve done before so if you like it you can check out a similar article I published here, leave a comment, or connect on LinkedIn. I have a lot of fun figuring out and breaking down problems so it’s always a pleasure to hear other perspectives. Anyway, enough on that, let’s get to it.

or function narcissistNumber(int){} works fine also

In this problem, we have to write an algorithm that can check if the integer input is a narcissistic number. Narcissistic numbers are whole numbers, or integers, whose digits each to the nth power sum to equal the whole number or integer itself, where nth is the number of digits.
You can find a list of Narcissistic numbers here.

The exponent of each digit is equal to the number of digits

My initial thought to solving this algorithm is to first split the integer input into an array of integers. In Javascript, this can be done with the Array.from() method, as demonstrated here. I’ll store the result in a variable digitArray.

I love using the primitive wrapper functions. Array(), String(), Number()…

Next, I would like to iterate through digitArray finding the nth power of each element where ’n’ is the length of the array (which is the same as the number of digits in our input integer). I’ll take each total and add it to a variable that will track the sum of the numbers in our digitArray as we iterate through so we can compare it with our original input later. We can use Math.pow() to find exponents in Javascript.

I like to write out what I’m about to create with comments before I start creating it

Lastly, after our loop breaks, we can compare our input with comparisonNum and conditional return a message telling us whether or not the input is a narcissistic number.

Some numbers are just more important

Then we can clean it up a bit to make it presentable.

A lot more readable without the comment clutter

To test this solution I ran the following tests:

Can you find any edge cases?

And the time complexity of our solution is O(n), linear time, where n is the length of the array we make from the digits of our input because we iterate over it once to find the solution.
Our space complexity is also O(n), linear space, where n is digitArray which, in our solution, is relative to the number of digits in the input integer.

Thanks for taking the time to read this, I hope you found it useful or perhaps took away some useful methods. If you can come up with a less complex solution I would love to hear about it.

Frontend Software Developer and Security Technician with experience in Ruby, Rails, JavaScript, and React. Flatiron Software Engineering Alumni.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store