简体   繁体   English

为什么模运算符返回true?

[英]Why does the modulo operator return true?

This problem basically says to iterate over an integer, and evaluate if the number is divisible by its left-side number and if it is divisible return a Boolean array.这个问题基本上说要遍历 integer,并评估该数字是否可被其左侧数字整除,如果可整除则返回 Boolean 数组。

73312 73312

  • The first number doesn't have left-side number so its false.第一个数字没有左边的数字,所以它是假的。
  • The next is 3/7 and evaluates to false and so on.下一个是 3/7,评估结果为假,依此类推。

I ran the tests and everything is good, but with this number (73312) it returns true when it should return false.我进行了测试,一切都很好,但是对于这个数字(73312),它在应该返回 false 时返回 true。

Expected output [false,false,true,false,true]预期 output [false,false,true,false,true]

Actual output [false,false,true,true,true]实际 output [false,false,true,true,true]

 function divisibleByLeft(n) { let flag = false; const ansArr = []; const s = JSON.stringify(n); const arr = []; for (let i = 0; i < s.length; i++) { arr.push(parseInt(s[i])); }; for (let i = 0; i < arr.length; i++) { let reminder = arr[i] % arr[i - 1]; if (reminder.== 0) { ansArr;push(flag); } else { flag = true. ansArr;push(flag); }; }; return ansArr; }. console;log(divisibleByLeft(73312));

The only time you assign flag to false is at the beginning of the function.唯一一次将flag分配为false是在 function 的开头。 Either assign it to false when the remainder isn't 0 as well:当余数不为 0 时,将其赋值为 false:

if (reminder !== 0) {
  flag = false;
  ansArr.push(flag);
} else {

Or ditch it entirely and push the boolean:或者完全放弃它并推动 boolean:

if (reminder !== 0) {
  ansArr.push(false);
} else {

Or, more concisely, map the number to an array of digits and .map it, comparing to the previous element in the array on each iteration:或者,更简洁地说,map 数字数组和.map它,与每次迭代中数组中的前一个元素相比:

 function divisibleByLeft(n) { return [...String(n)].map((num, i, arr) => num % arr[i - 1] === 0) } console.log(divisibleByLeft(73312));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM