Check Number is Even or Odd Using Bit Manipulation

Even numbers are multiples of 2, such as 2,4,6,8 and odd numbers are not multiple of 2 such as 3,5,7,9, etc. In binary representation, every even number has 0 at the 0th-bit position and an odd number have 1 at the 0th-bit position.

logical AND ( & )  of number with 1 will give 1 only if the last bit of both bits patterns are 1 other wise 0.

package org.wesome.dsalgo;

public class CheckEvenOdd {
    public static boolean checkEvenOdd(int number) {
        System.out.println(" in binary " + number + " will be " + Integer.toBinaryString(number));
        if ((number & 1) != 0) {
            System.out.println(number + " is odd");
            return false;
        } else {
            System.out.println(number + " is even");
            return true;
        }
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class CheckEvenOddTest {

    @Test
    void checkEven() {
        Assertions.assertTrue(CheckEvenOdd.checkEvenOdd(2));
    }

    @Test
    void checkOdd() {
        Assertions.assertFalse(CheckEvenOdd.checkEvenOdd(3));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on