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
import java.util.Scanner;
class evilno
{
String tobinary(int n)
{
String b="";
int r;
while(n!=0)
{
r=n%2;
b=Integer.toString(r)+b;
n=n/2;
}
return b;
}
public static void main(String args[])
{
evilno obj=new evilno();
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number: ");
int n=sc.nextInt();
int c=0;
String bin=obj.tobinary(n);
System.out.println("Binary equivalent is: "+bin);
for(int i=0;i<bin.length();i++)
{
if(bin.charAt(i)=='1')
c++;
}
if(c%2==0)
System.out.println("evilno");
else
System.out.println("Not evil no");
}
}