Evil Number in Java: Definition, Rules, Examples, and Practice Problems
An Evil Number is a positive integer whose binary representation contains an even number of 1s. These numbers are commonly asked in coding interviews and logical number theory exercises.
What Is an Evil Number?
A number is called an Evil Number if:
- You convert the number into binary.
- Count the number of 1s in the binary representation.
- If the count is even, the number is an Evil Number.
Example:
- 9 → binary is 1001 → contains two 1s → Evil Number
- 15 → binary is 1111 → contains four 1s → Evil Number
- 7 → binary is 111 → contains three 1s → not an Evil Number
Why Is It Called an Evil Number?
The name comes from the pairing with "Odious Numbers". In number theory, numbers with an even count of 1s in binary were whimsically named “Evil”, while those with an odd count were named “Odious”.
Java Program to Check Evil Number
Below is the Java program that checks if a number is an Evil Number:
import java.util.Scanner;
public class EvilNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
String binary = Integer.toBinaryString(num);
int count = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
count++;
}
}
if (count % 2 == 0) {
System.out.println(num + " is an Evil Number");
} else {
System.out.println(num + " is NOT an Evil Number");
}
}
}
Examples
| Number | Binary | Count of 1s | Evil Number? |
|---|---|---|---|
| 9 | 1001 | 2 | Yes |
| 15 | 1111 | 4 | Yes |
| 5 | 101 | 2 | Yes |
| 7 | 111 | 3 | No |
3 Practice Challenges
Challenge 1: Simple Check
Write a Java program that checks whether a number is an Evil Number without using Integer.toBinaryString().
Challenge 2: Count Evil Numbers
Given an array of numbers, count how many of them are Evil Numbers.
Challenge 3: Range Generator
Write a Java program to print all Evil Numbers between 1 and 1000.