I have a variable that the server gives me with a value, I need to know if the number is even or odd , but without using %2
:
$.ajax({
url:'/numero',
type:'POST',
success:function(num){
// ¿Qué hago con num para saber qué es?
// num.numero me da el valor del numero ej;5,7,2...
}
})
It's very simple: use the AND bitwise operator .
In binary, even numbers have the last bit set to 0 , while odd numbers have the last bit set to 1 :
Therefore:
I can't resist the moral : there are only
10
kinds of people: those who know binary and those who don't ;-)Divide the number by 2. Odd numbers will always return a decimal number while even numbers will not. Then it would only be necessary to verify if it is a decimal by converting the result to a string and search for the point:
Why don't you just do a division math operation? If when dividing a number by 2 the result of the division is exact, it means that the number is even, so we validate this with a regular expression, it is simply asking "if the result of the division contains a point, it means that it was not exact and that therefore Therefore the number is odd.
Knowing the last digit of your number you can decipher if the whole number is even or odd since it is known that the numbers ending in 0,2,4,6 and 8 are even, therefore
You can do the following:
//find if a number is even or odd without using modulus