1. 四则运算
准备工作:拆分项
构建的时候注意点是负数问题

计算:第一步:先消除括号(即优先计算括号里的)

第二步:计算乘除法

第三步:计算加减法
2. 质数因子

let num = 180; // 输入值
let y = 2; // 从2这个因子开始往后查询
let res = []; // 存质数因子
while (num !== 1) { // 一直到整除后结束
if (num % y === 0) { // 确保y是质数因子,如果能整除就push
res.push(y);
num = num / y;
continue;
}
// 如果无法整除,则y需要往后查询
// 这是这个题最重要的一点,y到num的开方就停止
// 如果num不是质数,那么说明num可以表示为n1*n2,
// n1和n2中一定是有一个数小于num的开方
// 当y已经大于那个开方值时还没有找到因子,说明这个num就是一个质数,那么不需要往后查询了
// y > Math.sqrt(num) 可以转为 y*y > num进行判断
if (y * y > num) {
y = num;
continue
}
y++;
}
console.log(res.join(' '))
3. 求数组指定长度连续子区间的最大和

var maxSatisfied = function (customers, grumpy, minutes) {
let sum = 0; // 已满意的客人总数量
customers.forEach((item, index) => {
if (grumpy[index] === 0) { // 没生气
sum += item;
customers[index] = 0; // 更新customers!!!
}
});
// 至此,customers存的是不满意的客户
// 接下来求customers中连续minutes的最大和:新区间的和 = 老区间的和 - 老区间第一个数 + 新区间最后一个数
let startIndex = customers.findIndex(item => item > 0);
if (startIndex < 0) { // 全都满意
return sum;
}
let sum2 = 0; // 连续和
// 先求前minutes个的连续和,之后再求和的时候就在这个基础上运算
for (let i = startIndex, end = Math.min(startIndex + minutes, customers.length); i < end; i++) {
sum2 += customers[i];
}
// 从下一个开始,求连续和,并取最大值
let max = sum2;
for (let i = startIndex + 1, end = customers.length - minutes; i <= end; i++) {
sum2 = sum2 - customers[i - 1] + customers[i + minutes - 1]; // 求连续和的逻辑!!!
if (sum2 > max) {
max = sum2;
}
}
return sum + max;
};
网友评论