0
How check a number whether even or odd using java script?
5 ответов
+ 3
You can use the number 2 with the modulus operator % (YourNumberHere%2) then do a check to see if it returns 0 or 1. if it returns 0, then the number is even. if it returns 1, the number is odd
when you have an even number you will get 0
var x = 10
var y=x%2
document.write(y) //writes 0.
when you have an odd number you will get 1
var x = 23
var y=x%2
document.write(y) //writes 1.
+ 2
Another option probably more efficient in case of intensive use, is to do a binary AND with one ( has behaviour to 'mask' all the not set to 1 bits, so get the value of the most right bit ) to have the same result as modulo two ( % 2 ) but without need to perform division ( as modulo ):
var x=10;
var y=x&1;
document.write(y); // writes 0.
x=23;
y=x&1;
document.write(y); // writes 1.
+ 1
for this you use the %(modulo) operator, for example 4%2 will return 0. whenever this return 0 the number is even, everything else is odd!
0
divide by 2, if it returns a float fail as even
0
var numToTest = 45;
var result;
if(numToTest%2===0){
result = "EVEN"
}
else{
result = "ODD"
}