LoginSignup
0
0

More than 5 years have passed since last update.

js 引数が各位の数と位置による数のべき乗の合計と等しいか

Last updated at Posted at 2018-05-09

与えられた数値が、各位の数字と位置による数字のべき乗の合計と等しいか判定する。
(詳しくは下記例を参照ください。)
正の場合はyes!! 偽の場合はnot!!を返す。
*与えられる数は常に正の数
*文字を返してください


f(89)// yes!!
$8^1$+ $9^2$ = 89
与えられた数と合計が一致する

f(564)//not!!
$5^1$+ $6^2$ + $4^3$ = 546
与えられた数と合計が一致しない

function f(n){
  //your code here

}

f(89);// yes!!
f(564);//not!!
f(135);// yes!!
f(136586);//not!!

使ったもの

String();
split();
for
Math.pow();
if

考えかた

与えられた数値を文字へ変換し、分割して配列にいれる。
for文で各位の数と位置の数をべき乗して合計していく。
最後に引数と合計した数を判定する。

コード

function f(n){
  //your code here
  let array = [];
  let sum = 0;
  let num = 0;  
  let str = String(n);
  array = str.split('');
  for(let i = 1 ; i <= array.length ; i++){
    num = Number(array[i -1]);
    sum += Math.pow(num, i)
  }

  return sum == n? 'yes!!':'not!!';
}
f(89);

その他コード

const f = (num) => (
  [...num + ''].reduce(
    (acc, n, i) => acc + Math.pow(n, i + 1), 0
  ) === num ? 'yes' : 'not'
) + '!!';

その他コード浮かんだ方、コメントお願いします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0