Evil Number in Java: Definition, Examples, and Practice Problems

Learn what an Evil Number is in Java and number theory. Understand its definition, binary representation rules, examples, and how to check Evil Numbers using Java. Includes example table and 3 practice challenges.

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:

Example:

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.