6kyu Does my number look big in this

题目:

A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits.

For example, take 153 (3 digits):

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
and 1634 (4 digits):

1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
The Challenge:

Your code must return true or false depending upon whether the given number is a Narcissistic number.

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

答案:

// 1
function narcissistic (value) {
  return ('' + value).split('').reduce (function (p, c) {
    return p + Math.pow(c, ('' + value).length)
  }, 0) == value;
}

// 2
function narcissistic (value) {
  var remaining = value,
    digits = [],
    solution = 0;
  while (remaining > 0) {
    digits.push(remaining % 10);
    remaining = Math.floor(remaining / 10);
  }

  return value == digits.reduce(function (p, n) {
    return p + Math.pow(n, digits.length);
  }, 0);
}

// 3
function narcissistic (value) {
  var value,
    arr = [],
    res = 0;
  if (value < 10) {
    return true;
  } else {
    arr = value.toString().split('').map(item => parseInt(item));
    for (var i = 0; i < arr.length; i++) {
      res += Math.pow(arr[i], arr.length);
    }
  return res == value ? true : false;
  }
}

posted @ 2017-08-07 09:19  tong24  阅读(251)  评论(0编辑  收藏  举报