Java program to check for Evil Number (ISC Specimen 2016 Question 1)
Java program to input a number and check whether it is an Evil Number or not.
Question:
Write a Program in Java to input a number and check whether it is an Evil Number or not.
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
Programming Code:
/**
* The class EvilNumber inputs a number and checks whether it is an Evil Number or not
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
* @ISC Computer Science Practical Specimen Paper - Question 1
*/
import java.util.*;
class EvilNumber
{
String toBinary(int n) // Function to convert a number to Binary
{
int r;
String s=""; //variable for storing the result
char dig[]={'0','1'}; //array storing the digits (as characters) in a binary number system
while(n>0)
{
r=n%2; //finding remainder by dividing the number by 2
s=dig[r]+s; //adding the remainder to the result and reversing at the same time
n=n/2;
}
return s;
}
int countOne(String s) // Function to count no of 1's in binary number
{
int c = 0, l = s.length();
char ch;
for(int i=0; i<l; i++)
{
ch=s.charAt(i);
if(ch=='1')
{
c++;
}
}
return c;
}
public static void main(String args[])
{
EvilNumber ob = new EvilNumber();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive number : ");
int n = sc.nextInt();
String bin = ob.toBinary(n);
System.out.println("Binary Equivalent = "+bin);
int x = ob.countOne(bin);
System.out.println("Number of Ones = "+x);
if(x%2==0)
System.out.println(n+" is an Evil Number.");
else
System.out.println(n+" is Not an Evil Number.");
}
}Output:
Enter a positive number : 26
Binary Equivalent = 11010
Number of Ones = 3
26 is Not an Evil Number.
Enter a positive number : 420
Binary Equivalent = 110100100
Number of Ones = 4
420 is an Evil Number.
Enter a positive number : 659
Binary Equivalent = 1010010011
Number of Ones = 5
659 is Not an Evil Number.