首页 > 解决方案 > 如何使用我的函数从 123456789 返回 305274961

问题描述

如果我们以 n=123456789 为例,我需要返回 305274961 我通过将 2 加到 1、3、5... 并减去 2 到 2、4、6... 来得到它。我已经使用 for循环和一些数组,但现在我需要组合这两个数组,然后使用 .join(' ') 函数将它们连接起来

function encryptMyCode(n) {

var spell = n.toString(10).split('')
    var arr1 =[]
    var arr2 =[]

    for(var i=0 ; i<spell.length; i=i+2){
        arr1.push((parseInt(spell[i])+2)%10);
    }
    for(var i=1 ; i<spell.length; i=i+2){
        arr2.push(Math.floor(parseInt(spell[i]-2)%10));
    }

    // if n = 123456789
    // arr1 = [ 3, 5, 7, 9, 1 ]
    // arr2 = [ 0, 2, 4, 6 ]
    // i want to return[3,0,5,2,7,4,9,6,1]
}

标签: javascript

解决方案


检查i % 2单个循环内部,并在根据结果进行加减时推送:

function encryptMyCode(n) {
  const inputArr = n.toString(10).split('');
  const result = [];
  for (let i = 0; i < inputArr.length; i++) {
    result.push((Number(inputArr[i]) + (i % 2 ? -2 : 2)) % 10);
  }
  return result;
}
console.log(encryptMyCode(123456789));

或者,使用.map,看起来更干净:

function encryptMyCode(n) {
  return n
    .toString(10)
    .split('')
    .map((num, i) => (Number(num) + (i % 2 ? -2 : 2)) % 10);
}
console.log(encryptMyCode(123456789));


推荐阅读