Evil Number Java Program – ISC Computer Practical Question

Question: An Evil number is a positive whole number which has even number of 1’s in its binary equivalent.

Example: Binary equivalent of 9 is 1001, which contains even number of 1’s.
Thus, 9 is an Evil Number.

A few Evil numbers are 3, 5, 6, 9….

Design a program to accept a positive whole number ‘N’ where N>2 and N<100. Find the binary equivalent of the number and count the number of 1s in it and display whether it is an Evil number or not with an appropriate message.

Test your program with the following data and some random data:

Example 1:
INPUT: N = 15
BINARY EQUIVALENT: 1111
NUMBER OF 1’s: 4
OUTPUT: EVIL NUMBER

Example 2:
INPUT: N = 26
BINARY EQUIVALENT: 11010
NUMBER OF 1’s: 3
OUTPUT: NOT AN EVIL NUMBER

Example 3:
INPUT: N = 145
OUTPUT: NUMBER OUT OF RANGE

import java.util.Scanner;
class Evil
{
    String toBinary(int n) // function to convert decimal number to binary
    {
        String b="";
        while(n>0)
        {
            int r = n%2;
            b = r + b;
            n/=2;
        }
        return b;
    }
    
    public static void main(String args[])
    {
        Evil obj = new Evil();
        Scanner ob = new Scanner(System.in);
        System.out.println("Enter a number N between 2 and 100");
        int n = ob.nextInt();
        if(n>2 && n<100)
        {
            String bin = obj.toBinary(n);
            System.out.println("INPUT: " + n);
            System.out.println("BINARY EQUIVALENT: " + bin);
            int c=0;
            for(int i=0; i<bin.length(); i++)
            {
                if(bin.charAt(i) == '1')
                    c++;
            }
            System.out.println("NUMBER OF 1's: " + c);
            
            if(c%2==0)
                System.out.println("EVIL NUMBER");
            else
                System.out.println("NOT AN EVIL NUMBER");
        }
        else
        {
            System.out.println("NUMBER OUT OF RANGE");
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *