检查奇数,无需模运算符

时间:2017-06-23 05:29:17

标签: javascript

我正在创建一个函数,它返回传入的数字是否为奇数而没有模运算符。棘手的部分是它应该适用于负数和零。

到目前为止,这是我的代码:

function testodd(num) {
  return (num/2)*2==num;
}

var output = testodd(17);
console.log(output); // --> true

我在这里犯了一些错误吗?或者有更好的方法吗?

9 个答案:

答案 0 :(得分:7)

您可以使用Bitwise运算符并获得相同的结果。这有帮助。

<script type="text/javascript">
   function oddOrEven(x) {
       return ( x & 1 ) ? "odd" : "even";
   }    
   console.log(oddOrEven(10));
</script>

有关bitwise operator

的详细信息

答案 1 :(得分:6)

您好,您可以使用按位AND(&amp;)运算符来检查数字是偶数还是奇数。

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

答案 2 :(得分:4)

使用Math.floor删除除法后的小数部分。

Math.floor(num / 2) * 2 === num;

对于偶数,十进制值没有损失。对于奇数,小数点值将丢失,比较将为假。

答案 3 :(得分:3)

尝试逐位操作

function testodd(num) {
  return num & 1; // num AND 0x1 checks for the least significant bit, indicating true or falsey
}

答案 4 :(得分:1)

由于已经有了答案,我将向您展示使用regex

进行替代的方法
function checkOdd(num){
  console.log(/^\d*[13579]$/.test(num));
}

checkOdd(105);
  

只能使用合理大小的整数

答案 5 :(得分:1)

这是一种使用递归的非常低效的方法:

java:jboss/exported/

当然你永远不应该使用它。

答案 6 :(得分:0)

尝试

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);
}

答案 7 :(得分:0)

使用此功能可以检查数字是否为奇数或偶数,而无需使用模运算符%。这应该适用于负数和零。

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
}

答案 8 :(得分:0)

您可以使用isInteger方法

function isEven(n){
   return Number.isInteger(n / 2);
}