C Programs Tutorials | IT Developer
IT Developer

Java Programs - Advanced



Share with a Friend

Evil Number Program - Java Program

Design a class Evil to check if a given number is an evil number or not. A number is said to be evil if the binary equivalent of the number contains even number of 1s.

Example: If the number is 17, then its binary equivalent = 10001 (which contains even number of 1s). Thus, 17 is an evil number.

Some of the members of the class are given below:

Class name: Evil
Data members/instance variables:
num: to store a positive integer

Methods/Member functions:
Evil(): default constructor to initialize the data member with legal initial value
void getnum(): to accept a positive integer
int bin_convert(int n): returns the binary equivalent of the integer parameter ‘n’ using recursive technique

void isEvil(): checks whether the given number is an evil number by invoking the function bin_convert() and displays the result with an appropriate message

Specify the class Evil giving details of the constructor(), void getnum(), int bin_convert(int) and void isEvil(). Define a main() function to create an object and call the functions accordingly to enable the task.

 

import java.util.Scanner; class Evil{ int num; public Evil(){ num = 0; } public void getnum(){ Scanner in = new Scanner(System.in); System.out.print("Enter a positive integer: "); num = Integer.parseInt(in.nextLine()); num = Math.abs(num); } public int bin_convert(int n){ if(n == 0 || n == 1) return n; return bin_convert(n / 2) * 10 + n % 2; } public void isEvil(){ int count = 0; int bin = bin_convert(num); System.out.println("BINARY EQUIVALENT: " + bin); while(bin > 0){ if(bin % 10 == 1) count++; bin /= 10; } if(count % 2 == 0) System.out.println("EVIL NUMBER"); else System.out.println("NOT AN EVIL NUMBER"); } public static void main(String[] args){ Evil obj = new Evil(); obj.getnum(); obj.isEvil(); } }

Output

 

OUTPUT 1: 
Enter a positive integer: 5
BINARY EQUIVALENT: 101
EVIL NUMBER

OUTPUT 2: 
Enter a positive integer: 17
BINARY EQUIVALENT: 10001
EVIL NUMBER

OUTPUT 3: 
Enter a positive integer: 16
BINARY EQUIVALENT: 10000
NOT AN EVIL NUMBER