Programming Examples
Java program for Evil Number
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
Solution
import java.util.*;
class EvilNumber
{
String toBinary(int n)
{
int r;
String s="";
char dig[]={'0','1'};
while(n>0)
{
r=n%2;
s=dig[r]+s;
n=n/2;
}
return s;
}
int countOne(String s)
{
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 : 15
Binary Equivalent = 1111
Number of Ones = 4
15 is an Evil Number.
Enter a positive number : 420
Binary Equivalent = 110100100
Number of Ones = 4
420 is an Evil Number.
Enter a positive number : 3
Binary Equivalent = 11
Number of Ones = 2
3 is an Evil Number.
Enter a positive number : 26
Binary Equivalent = 11010
Number of Ones = 3
26 is Not an Evil Number.