How do I check if an integer is even or odd using bitwise operators
Also in Java you will have to use if((number&1)==1){//then odd}
, because in Java and C# like languages the int
is not casted to boolean
. You'll have to use the relational operators to return
a boolean
value i.e true
and false
unlike C and C++ like languages which treats non-zero value as true
.
if(x & 1) // '&' is a bit-wise AND operator
printf("%d is ODD\n", x);
else
printf("%d is EVEN\n", x);
Examples:
For 9:
9 -> 1 0 0 1
1 -> & 0 0 0 1
-------------------
result-> 0 0 0 1
So 9 AND 1 gives us 1, as the right most bit of every odd number is 1.
For 14:
14 -> 1 1 1 0
1 -> & 0 0 0 1
------------------
result-> 0 0 0 0
So 14 AND 1 gives us 0, as the right most bit of every even number is 0.
if (number & 1)
number is odd
else // (number & 1) == 0
number is even
For example, let's take integer 25, which is odd.
In binary 25 is 00011001
. Notice that the least significant bit b0
is 1.
00011001
00000001 (00000001 is 1 in binary)
&
--------
00000001
In Java,
if((num & 1)==0){
//its an even num
}
//otherwise its an odd num
You can do it simply using bitwise AND &
operator.
if(num & 1)
{
//I am odd number.
}
Read more over here - Checking even odd using bitwise operator in C
#include <iostream>
#include <algorithm>
#include <vector>
void BitConvert(int num, std::vector<int> &array){
while (num > 0){
array.push_back(num % 2);
num = num / 2;
}
}
void CheckEven(int num){
std::vector<int> array;
BitConvert(num, array);
if (array[0] == 0)
std::cout << "Number is even";
else
std::cout << "Number is odd";
}
int main(){
int num;
std::cout << "Enter a number:";
std::cin >> num;
CheckEven(num);
std::cout << std::endl;
return 0;
}