zoukankan      html  css  js  c++  java
  • JavaScript 找出特殊数字如135 = 1^1 + 3^2 + 5^3

    Description:

    The number' '89' 'is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What's the use of saying "Eureka"? Because this sum gives the same number.

    In effect: 89 = 8^1 + 9^2

    The next number in having this property is 135.

    See this property again: 135 = 1^1 + 3^2 + 5^3

    We need a function to collect these numbers, that may receive two integers 'a', 'b' that defines the range '[a, b]' (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.

    Let's see some cases:

    console.log(sumDigPow(1, 10));    //[1, 2, 3, 4, 5, 6, 7, 8, 9]
    console.log(sumDigPow(1, 200));   //[1, 2, 3, 4, 5, 6, 7, 8, 9, 89, 135, 175]
    console.log(sumDigPow(99, 100));  //[]
    

    my answer:

    function sumDigPow(a, b) {
      var arr = [];
      for (var i = a; i <= b; i++) {
        var sum = 0;
        for (var j = 0; j <= String(i).length; j++) {
          sum += Math.pow(parseInt(String(i)[j]), j+1);  
          if (sum === i) arr.push(i);
        }
      }
      return arr;
    }
    

    other answer:

    • forEach方法
    function sumDigPow(a, b) {
      var c = a, result =[];
      while(c < b){
        var sum = 0;
        (c+'').split('').forEach(function(v, i){
          sum += Math.pow(v, i+1);
        });
        if(c === sum)result.push(c);
        c++;
      }
      return result;
    }
    
    • forEach方法中的function回调有三个参数:第一个参数是遍历的数组内容,第二个参数是对应的数组索引,第三个参数是数组本身
    var arr = [1,2,3,4];
    arr.forEach(alert);
    

    等价于:

    var arr = [1, 2, 3, 4];
    for (var k = 0, length = arr.length; k < length; k++) {
     alert(array[k]);
    }
    

    比如:

    var arr = [1,2,3,4];
    arr.forEach(function(value,index,array){
        array[index] == value;    //结果为true
        sum+=value;  
        });
    console.log(sum);    //结果为 10
    
  • 相关阅读:
    RDLC报表中浮点型设置精度设置小数位位数
    C# 设置DateTime类型的变量值等于Null
    我的2011就这样混掉了
    RDLC报表改动的注意事项之增加字段和参数
    (分享)C# 绘制统计图(柱状图, 折线图, 扇形图)
    C#实现Winform自定义半透明遮罩层
    C#中判断网络连接的状态
    su 和 sudo、su root和su root 区别
    嵌入式系统软件优化方法
    ARM开发步步深入之定时加速
  • 原文地址:https://www.cnblogs.com/kid2333/p/7462384.html
Copyright © 2011-2022 走看看