Skip to content

Commit 964ba04

Browse files
fix: optimised armstrongNumber code (TheAlgorithms#1374)
1 parent 394483b commit 964ba04

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

Maths/ArmstrongNumber.js

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,13 @@
99
*/
1010

1111
const armstrongNumber = (num) => {
12-
if (num < 0 || typeof num !== 'number') return false
13-
14-
let newSum = 0
15-
16-
const numArr = num.toString().split('')
17-
numArr.forEach((num) => {
18-
newSum += parseInt(num) ** numArr.length
19-
})
20-
21-
return newSum === num
12+
if (typeof num !== 'number' || num < 0) return false
13+
const numStr = num.toString()
14+
const sum = [...numStr].reduce(
15+
(acc, digit) => acc + parseInt(digit) ** numStr.length,
16+
0
17+
)
18+
return sum === num
2219
}
2320

2421
export { armstrongNumber }

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy