Google News
logo
Java Program to Evil Number
An evil number is a non-negative integer that has an even number of 1s in its binary representation. Here's a Java program to check if a number is evil or not :
Program :
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 n = sc.nextInt();
        int count = 0;
        while (n != 0) {
            if ((n & 1) == 1) {
                count++;
            }
            n >>= 1;
        }
        if (count % 2 == 0) {
            System.out.println("The number is evil");
        } else {
            System.out.println("The number is not evil");
        }
    }
}
Output :
Enter a number: 3
The number is evil
Enter a number: 13
The number is not evil
In this program, we first take input from the user and store it in the variable n. Then, we count the number of 1s in the binary representation of n using a while loop. In each iteration, we check if the least significant bit of n is 1 using the bitwise AND operator (&).

If it is, we increment the count variable. Finally, we check if count is even or odd to determine if the number is evil or not.