JS数组相关几道算法面试题

前端小测-JS 算法题目(数组相关):

将数字转为整数数组:

已知数组:

1
let num = 13579; // => [1,3,5,7,9];
1
2
3
4
5
6
7
8
let num = 13579;
let convertArray = (num) => {
return num
.toString()
.split("")
.map((item) => parseInt(item));
};
console.log(convertArray(num));

实现整数反转,一定要注意参数是负数的坑

1
2
let a = 456,
b = -654;
1
2
3
4
5
6
7
let revNum = (num) => {
return num > 0
? parseInt(num.toString().split("").reverse().join(""))
: -parseInt(num.toString().split("").reverse().join(""));
};

console.log("result", revNum(456), revNum(-654));

给定一个数组,数组[动态和]

1
2
3
4
给你一个数组nums,数组[动态和]的计算公式为:runningSum = sum(nums[0],...nums[i])
请返回 nums 的动态和
输入:nums = [1,2,3,4]
输出:result = [1,3,6,10]

方法 1:双重循环

1
2
3
4
5
6
7
8
9
10
11
12
13
const runningSum = function (nums) {
let res = [];
for (let i = 0; i < nums.length; i++) {
let acc = 0;
for (let j = 0; j <= i; j++) {
acc += nums[j];
}
res.push(acc);
}
return res;
};

console.log("result", runningSum(nums));

方法 2:动态规划

1
2
3
4
5
6
7
8
const runningSum2 = function (nums) {
nums.reduce((pre, cur, index) => {
nums[index] = pre + cur;
return nums[index];
});
return nums;
};
console.log("result", runningSum2(nums));