javascript - 如何使用我的函数从 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]
}
解决方案
检查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));
推荐阅读
- android - Unity游戏中出现广告时如何重启手机?
- flutter - Flutter v1.0下的类TickerProviderStateMixin undefined
- java - 如何在 selenium 中使用 java 从 excel 工作表中检索 0.00000000 等十进制值?
- excel - VBA - 选择指定范围时在下一个单元格上调用函数
- vba - 需要建议或帮助来修改可以在通配符搜索 VBA 后搜索子字符串和格式的宏
- java - java spring bean factory可以返回bean列表吗?
- postgresql - PostgreSQL 安装错误,当位于 C:\Program Files (X86)\ 的 App 目录中时,带有“--”前缀
- html - 百分比和视口高度/宽度没有调整与格式化文本相关的比例
- python - 如何阻止第二个 PyQt5 QMainWindow 关闭?
- c# - 无法访问子页面中动态调用的用户控件中的控件