I am learning js and struggling with a problem I encountered on Codewars.
I need to calculate how many numbers containing only binary digits exist between 1 and a random number n. For example, if n is 20, there are 3 such numbers: 1, 10, 11;
I have written a solution that works on codepen but Codewars is telling me it is too inefficient to be accepted. I can’t think of anything else I can do to optimize it. Thank you in advance for your help!
function incompleteVirus(n) {
let countInMemory = 0;
let isBinary = true;
// Loop through all numbers below and including n
for (let i = 1; i <= n; i++) {
let strCurrNum = String(i);
// Iterate through all digits in the current number
for (const digit of strCurrNum) {
let numDigit = Number(digit);
// Check if each digit is binary; if not, exit loop
if (numDigit > 1) {
isBinary = false;
break;
} else {
isBinary = true;
}
}
// Update memory count
if (isBinary) {
countInMemory += 1;
}
}
return countInMemory
}