英文:
Javascript, how to use !- NOT operator
问题
I try to solve Javascript kata at codewars:
*如果我们列出所有小于10的自然数,这些数是3或5的倍数,我们得到3, 5, 6和9。这些倍数的总和是23。
完成这个解决方案,以便它返回小于传入数字的所有3或5的倍数的总和。此外,如果数字为负数,返回0(对于具有负数的语言)。
注意:如果数字既是3的倍数又是5的倍数,只计数一次。
由projecteuler.net提供(问题1)
*
有人能解释一下为什么我的代码返回错误的值吗?我认为这是由于NOT运算符。
function solution(number){
let result = 0
if (number < 0)
return 0
for (let i = 1; i < number; i++){
if ((number - i) % 3 === 0)
{result = result + (number / 3)
}
}
for (let j = 1; j < number; j++)
if ((number - j) % 5 === 0 && !((number - j) % 3) === 0)
{result = result + (number / 5)
}
return result
}
英文:
I try to solve Javascript kata at codewars:
*If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. Additionally, if the number is negative, return 0 (for languages that do have them).
Note: If the number is a multiple of both 3 and 5, only count it once.
Courtesy of projecteuler.net (Problem 1)
*
Can someone please explain me why my code returns false values? I believe it is due to NOT operator.
function solution(number){
let result = 0
if (number<0)
return 0
for (let i=1; i<number; i++){
if ((number-i)%3===0)
{result = result + (number/3)
}
}
for (let j=1; j<number; j++)
if ((number-j)%5===0 && (!(number-j)%3)===0)
{result = result + (number/5)
}
return result
}
答案1
得分: 1
以下是翻译好的内容:
function solution(lim) {
let result = 0;
for (let i = 1; i < lim; i++) {
if (i % 3 === 0 || i % 5 === 0) {
result += i;
}
}
return result;
}
console.log(
solution(10)
,solution(-1)
,solution(0)
)
// 23 0 0
...更容易测试是否能同时被3或5整除,而不是两次。
英文:
Might be easier to simplify the code to something like:
function solution(lim) {
let result = 0
for (let i = 1; i < lim; i++) {
if (i % 3 === 0 || i % 5 === 0) {
result += i
}
}
return result
}
console.log(
solution(10)
,solution(-1)
,solution(0)
)
// 23 0 0
...it's easier to test for divisibily by 3 or 5 in one go, rather than twice.
答案2
得分: 0
以下是翻译好的代码部分:
function* range(inc, max) {
let i=0;
while((i+=inc)<max) yield i;
}
function solution(n) {
return n<0?0:[...new Set([...range(3,n),...range(5,n)])].reduce((a,b)=>a+b)
}
console.log(solution(10))
英文:
Just for fun, the ES6 way:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function* range(inc, max) {
let i=0;
while((i+=inc)<max) yield i;
}
function solution(n) {
return n<0?0:[...new Set([...range(3,n),...range(5,n)])].reduce((a,b)=>a+b)
}
console.log(solution(10))
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论