# Evil number program in Java

## ISC Computer Science Specimen Question Paper 2016 (Q1, Evil number)

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.
A few evil numbers are 3, 5, 6, 9….

Design a program to accept a positive whole number and find the binary equivalent of the number and count the number of 1’s in it and display whether it is a Evil number or not with an appropriate message.
Output the result in format given below:
Example 1
INPUT : 15
BINARY EQUIVALENT : 1111
NO. OF 1’s : 4
OUTPUT : EVIL NUMBER
Example 2
INPUT : 26
BINARY EQUIVALENT : 11010
NO. OF 1’s : 3
OUTPUT : NOT AN EVIL NUMBER

The logic is fairly straightforward, one has to enter the number, convert it into binary and count the number of 1s. Since the question is specifically asking for printing the binary equivalent I would suggest the use of the function toBinaryString of Integer class to ease the coding process. The java program for evil number detection is as follows:

```import java.util.*;
class EvilNumber{
public static void main( String args[] ){
Scanner sc = new Scanner(System.in);
System.out.print("INPUT\t\t\t: ");
int n = sc.nextInt();
if(n>0){
//convert to binary using the library function toBinaryString()
String nBinary = Integer.toBinaryString( n );
System.out.println( "BINARY EQUIVALENT\t: " + nBinary );
int oneCount=0;
for( int i=0; i<nBinary.length(); i++ ){
if( nBinary.charAt( i ) == '1' ) oneCount++;
}
System.out.println( "NO. OF 1's\t\t: " + oneCount );
System.out.print( "OUTPUT\t\t\t: " );
if( oneCount % 2 == 0 ){
System.out.println( "EVIL NUMBER" );
}else{
System.out.println( "NOT AN EVIL NUMBER" );
}
}else System.out.println( "Invalid Input" );
}
}```

The output of the above program to ascertain the unique number would be as follows:

```INPUT			: 15
BINARY EQUIVALENT	: 1111
NO. OF 1's		: 4
OUTPUT			: EVIL NUMBER

INPUT			: 26
BINARY EQUIVALENT	: 11010
NO. OF 1's		: 3
OUTPUT			: NOT AN EVIL NUMBER
```

The ISC Computer Science Question Paper for 2016 is available here.