英文:
loop that count to 100 and replace with some text any number that divide by 3 or conatins number 3
问题
function checker(num) {
for (i = 1; i <= num; ++i) {
if (i % 3 === 0 || i.toString().includes('3')) {
console.log('boom');
} else {
console.log(i);
}
}
}
checker(100);
英文:
function checker (num){
for(i = 1; i <= num; ++i){
if(i % 3 === 0 ||
i === 13 ||
i === 23 ||
i === 33 ||
i === 43 ||
i === 53 ||
i === 63 ||
i === 73 ||
i === 83 ||
i === 93){
console.log('boom')
}
else{
console.log(i)
}
}
}
checker(100)
so i made this , but thats looks ugly , how to do it correct ? like any number that contains 3 replace it with some text. thank you.
答案1
得分: 2
你可以检查字符串,也可以检查以下部分。
if (i % 3 === 0 || i.toString().includes('3')) ...
英文:
You could check the string, too.
if (i % 3 === 0 || i.toString().includes('3')) ...
答案2
得分: 1
If your loop only counts to 100, you only need to check the tens and ones place to determine if it's a 3
. You can use the JavaScript modulo operator %
and the Math.floor()
static method:
if (Math.floor(i / 10) === 3 || i % 10 === 3 || i % 3 === 0) // ...
The Math.floor
method will return true if dividing the number by 10 and rounding down returns 3 (true
for the numbers 30
to 39
inclusive), and the %
modulo operator will return true
when dividing i
by 10 has a remainder of 3
(true for 3
, 13
, 23
, 33
, etc.) i % 3 === 0
is from your original function.
英文:
If your loop only counts to 100, you only need to check the tens and ones place to determine if it's a 3
. You can use the JavaScript modulo operator %
and the Math.floor()
static method:
if (Math.floor(i / 10) === 3 || i % 10 === 3 || i % 3 === 0) // ...
The Math.floor
method will return true if dividing the number by 10 and rounding down returns 3 (true
for the numbers 30
to 39
inclusive), and the %
modulo operator will return true
when dividing i
by 10 has a remainder of 3
(true for 3
, 13
, 23
, 33
, etc.) i % 3 === 0
is from your original function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论