Playing with digits


Description:


Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
  • we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n.
  • In other words:
    Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k
    If it is the case we will return k, if not return -1.
    Note: n and p will always be given as strictly positive integers.
    digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
    digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
    digPow(695, 2) should return 2 since 6² + 9³ + 5= 1390 = 695 * 2
    digPow(46288, 3) should return 51 since 4³ + 6+ 2+ 8+ 8= 2360688 = 46288 * 51

    My solution:

    function digPow(n, p){
      let array = [];
      let m = n;
      
      function reducer(acc,curr, index) {
        acc = acc + Math.pow(curr, index+p);
        return acc;
      }
      
      while(true) {
        let unit = n % 10;
        array.push(unit);
        
        n = (n-unit) / 10;
        if(n == 0) {
          break;
        }
      }
      
      array = array.reverse();
      const testNumber = array.reduce(reducer, 0);
      const k = testNumber / m;
      
      if(Number.isInteger(k) == true) {
        return k;
      }
      else {
        return -1; 
      }
      
    }

    Best solutions:

    function digPow(n, p) {
      var x = String(n).split("").map(a=>parseInt(a)).reduce((s, d, i) => s + Math.pow(d, p + i), 0)
      return x % n ? -1 : x / n
    }

  • String(number).split("").map(a⇒parseInt(a))
    各ビット数を要素とする配列を作成するには、まず数値を文字列に変換し、各文字を要素とする配列を作成します.それから各要素を数字に変換します.

  • condition ? exprIfTrue : exprIfFalse
    if文の略記バージョン.残りのコードが0の場合、条件はfalseであり、exprIfFalseが実行され、残りのコードがtrueの場合、exprIfTrueが実行されます.