/** * @param {number}L * @param {number}R * @return {number} */ var countPrimeSetBits = function (L, R) { const judge = (num) => { if (num < 2) returnfalse; for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) returnfalse; } returntrue; }; let count = 0; for (let i = L; i <= R; i++) { const len = i .toString(2) .split("") .filter((e) => e === "1").length; if (judge(len)) count++; } return count; };
改进
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * @param {number}L * @param {number}R * @return {number} */ var countPrimeSetBits = function (L, R) { const prime = newSet([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]); let count = 0; for (let i = L; i <= R; i++) { let len = 0; for (const num of i.toString(2)) if (num === "1") len++; if (prime.has(len)) count++; } return count; };