[英]Check Odd numbers without modulo operator
我正在创建一个函数,该函数在没有模运算符的情况下返回传入的数字是否为奇数。 棘手的部分是它应该适用于负数和零。
到目前为止,这是我的代码:
function testodd(num) {
return (num/2)*2==num;
}
var output = testodd(17);
console.log(output); // --> true
我在这里犯了一些错误吗? 或者有没有更好的方法来做到这一点?
您可以使用Bitwise
运算符并获得相同的结果。 这有帮助吗。
<script type="text/javascript">
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
console.log(oddOrEven(10));
</script>
有关 按位运算符的更多详细信息
嗨,您可以使用按位 AND (&) 运算符来检查数字是偶数还是奇数。
function testodd(num) {
if((num & 1) == 0){
return true
}
return false;
}
var output = testodd(17);
console.log(output); // --> false
var output = testodd(-16);
console.log(output); // --> true
var output = testodd(0);
console.log(output); // --> true
使用Math.floor
去除除法后的小数部分。
Math.floor(num / 2) * 2 === num;
对于偶数,十进制值没有损失。 对于奇数,小数点值会丢失,比较结果为假。
尝试按位操作
function testodd(num) {
return num & 1; // num AND 0x1 checks for the least significant bit, indicating true or falsey
}
由于已经有了答案,我将向您展示使用regex
进行操作的替代方法
function checkOdd(num){
console.log(/^\d*[13579]$/.test(num));
}
checkOdd(105);
仅适用于合理大小的整数
这是使用递归的一种非常低效的方法:
function checkOdd(num)
{
num = Math.abs(num);
if(num==0)
return false;
else if(num==1)
return true;
else
return checkOdd(num-2);
}
当然,您永远不应该使用它。
试试
function testodd(num){
if num < 0{
var number = -num
}
int i = 1;
int product = 0;
while (product <= num)
{
product = divisor * i;
i++;
}
// return remainder
return num - (product - divisor);
}
使用此函数检查数字是奇数还是偶数,而不使用模运算符%
。 这应该适用于负数和零。
function checkOdd(num) {
// your code here
if(num<0){ //Check if number is negative
num=-num; //Convert it into positive number
}
let b=Math.floor(num/2) //Taking value for loop iteration
for(var i=1;i<=b;i++){
num=num-2; //Will check the number is odd if it subtraction end to 1 by decrementing -2 to the number
if(num==1){
return true; //return true if number is odd
}
}
return false; //return false if number is even
}
您可以使用 isInteger 方法
function isEven(n){
return Number.isInteger(n / 2);
}
function odd(num) {
if (num === 0) {
返回假; }
num = Math.abs(num);
而(数量> = 2){
数量 = 数量 - 2; }
如果(数量 === 1){
返回真; } 别的 {
return false;
}
}
让我们取一个偶数说 6; 6 除以 2 是 3;
Math.round(3) is 3;
Math.floor(3) is 3;
; 3===3 计算为真,所以 6 是偶数;
奇数让我们取一个奇数,比如 9; 9 除以 2 是 4.5;
Math.round(4.5) 是 5; Math.floor(4.5) 是 4;
5===4 的计算结果为假,所以 9 是奇数;
function evenChecked(num) {
if (Math.round(num / 2) === Math.floor(num / 2)) {
return `${num} is even`;
} else {
return `${num} is odd`;
}
}
console.log(evenChecked(23));
console.log(evenChecked(90));
console.log(evenChecked(56));
console.log(evenChecked(49));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.