BAEL-5560 - checking even and odd numbers (#12388)

This commit is contained in:
tudormarc
2022-06-24 06:57:48 +03:00
committed by GitHub
parent 69d21288b9
commit 20dc126a64
5 changed files with 141 additions and 0 deletions
@@ -0,0 +1,46 @@
package com.baeldung.evenodd;
public class EvenOdd {
static boolean isEven(int x) {
return x % 2 == 0;
}
static boolean isOdd(int x) {
return x % 2 == 1;
}
static boolean isOrEven(int x) {
return (x | 1) > x;
}
static boolean isOrOdd(int x) {
return (x | 1) == x;
}
static boolean isAndEven(int x) {
return (x & 1) == 0;
}
static boolean isAndOdd(int x) {
return (x & 1) == 1;
}
static boolean isXorEven(int x) {
return (x ^ 1) > x;
}
static boolean isXorOdd(int x) {
return (x ^ 1) < x;
}
static boolean isLsbEven(int x) {
return Integer.toBinaryString(x)
.endsWith("0");
}
static boolean isLsbOdd(int x) {
return Integer.toBinaryString(x)
.endsWith("1");
}
}
@@ -0,0 +1,68 @@
package com.baeldung.evenodd;
import static com.baeldung.evenodd.EvenOdd.isAndEven;
import static com.baeldung.evenodd.EvenOdd.isAndOdd;
import static com.baeldung.evenodd.EvenOdd.isEven;
import static com.baeldung.evenodd.EvenOdd.isLsbEven;
import static com.baeldung.evenodd.EvenOdd.isLsbOdd;
import static com.baeldung.evenodd.EvenOdd.isOdd;
import static com.baeldung.evenodd.EvenOdd.isOrEven;
import static com.baeldung.evenodd.EvenOdd.isOrOdd;
import static com.baeldung.evenodd.EvenOdd.isXorEven;
import static com.baeldung.evenodd.EvenOdd.isXorOdd;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class EvenOddUnitTest {
@Test
public void whenNumberIsEven_thenReturnTrue() {
assertEquals(true, isEven(2));
}
@Test
public void whenNumberIsOdd_thenReturnTrue() {
assertEquals(true, isOdd(3));
}
@Test
public void whenNumberIsEven_thenReturnTrueWithOr() {
assertEquals(true, isOrEven(4));
}
@Test
public void whenNumberIsOdd_thenReturnTrueOr() {
assertEquals(true, isOrOdd(5));
}
@Test
public void whenNumberIsEven_thenReturnTrueAnd() {
assertEquals(true, isAndEven(6));
}
@Test
public void whenNumberIsOdd_thenReturnTrueAnd() {
assertEquals(true, isAndOdd(7));
}
@Test
public void whenNumberIsEven_thenReturnTrueXor() {
assertEquals(true, isXorEven(8));
}
@Test
public void whenNumberIsOdd_thenReturnTrueXor() {
assertEquals(true, isXorOdd(9));
}
@Test
public void whenNumberIsEven_thenReturnTrueLsb() {
assertEquals(true, isLsbEven(10));
}
@Test
public void whenNumberIsOdd_thenReturnTrueLsb() {
assertEquals(true, isLsbOdd(11));
}
}