-
Notifications
You must be signed in to change notification settings - Fork 0
/
does-my-number-look-big-in-this.js
48 lines (37 loc) · 1.52 KB
/
does-my-number-look-big-in-this.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Does my number look big in this?
/*
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).
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.
*/
// function narcissistic(num){
// let str = num.toString();
// let len = str.length;
// let arr = str.split('');
// for(let i = 0; i < arr.length; i++){
// arr[i] = Math.pow(+arr[i], len);
// };
// arr = arr.reduce((acc,c)=>acc+c,0)
// return +str === arr
// }
const narcissistic = n => {
let arr = n.toString().split('');
for(let i = 0; i < arr.length; i++){
arr[i] = Math.pow(+arr[i], n.toString().length);
}
arr = arr.reduce((acc,c)=>acc+c,0);
return n === arr
}
// alternate solution
const narcissisticAgain = value => {
return ('' + value).split('').reduce(function(p, c){
return p + Math.pow(c, ('' + value).length)
}, 0) == value;
}
const x = 153;
console.log(narcissistic(x) === true)