Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Odd numbers without modulo operator

Tags:

javascript

I am creating a function that returns whether the passed in number is odd Without the modulo operator. The tricky part is that it should work for NEGATIVE numbers and ZERO.

here's my codes so far:

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

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

Am I making some mistakes here? Or is there a better way to do this?


1 Answers

you can use Bitwise operator and get same result. does this help.

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

For more detail about bitwise operator

like image 196
Dharmesh Rakholia Avatar answered Mar 15 '26 19:03

Dharmesh Rakholia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!