前端javascript:经典编程“神奇的数字”

281 阅读1分钟

题目来源:牛客网

在这个特殊的假期里,由于牛牛在家特别无聊,于是他发明了一个小游戏,游戏规则为:将字符串数字中为偶数位的数字进行翻转,将翻转后的结果进行输出。
示例1
输入
"1234"
输出
"1432"
说明
第2、4位为偶数,所以将其翻转后,得到 1432
示例2
输入
"12346"
输出
"16342"
说明
第2、4、5位为偶数,所以将其翻转后,得到 16342

备注:
数字的长度<=10^7 且不包含数字0  

我的解题思路:

  • 将字符串进行数组化,string.split(' ');

  • forEach遍历出所有偶数的下标;

  • 通过for循环进行原字符串数组偶数互换位置;

  • 通过array.join(' ');将数组以字符串形式拼接返回;

    /**
    * 
    * @param number string字符串 
    * @return string字符串
    */
    function change( number ) {
      // write code here
      let numArray=number.split('');
      let numIndexArray=[];
      numArray.forEach(function(value,index,arr){
          if((value-0)%2==0){
              numIndexArray.push(index);
          }
      });
      //获取到了所有偶数的下标;
     // 将numArray数组对称置换下标为numIndexArray元素的数组元素;
      let numIndexLen= numIndexArray.length;
      for(let i=0;i<numIndexLen/2;i++){
          // 利用ES6中的解构赋值:互换位置;
              [numArray[numIndexArray[i]],numArray[numIndexArray[numIndexLen-i-1]]]=[numArray[numIndexArray[numIndexLen-i-1]],numArray[numIndexArray[i]]]
          }
      return numArray.join('');
    }
    module.exports = {
      change : change
    };
    

欢迎留下你的最优解