Write a Program in Java to input a number and check whether it is an Evil Number or not. 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 other evil numbers are 3, 5, 6.
Answers
/* Program for Evil Number
* Code is given, and screenshots are also attached
*/
import java.util.Scanner; //Importing Scanner Object
public class EvilNumber
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //Creating Scanner Object
System.out.print("Enter a number: "); //Asking for user input
int n = sc.nextInt(); //Scanning user input
int cnt=count(toBin(n)); //Calling the toBin(n) function, and applying count() function on it
if(cnt%2==0) //If there are even number of "1"s in binary, then it is Evil
{
System.out.println(n+" is an Evil Number.");
}
else
{
System.out.println(n+" is not an Evil Number.");
}
}
static String toBin(int n) //Function to convert number into binary equivalent
{
String str=""; //Start with a null string
while(n>0)
{
if(n%2==0)
{
str="0"+str; //If n is divisible by 2, then we append 0 at the beginning
}
else
{
str="1"+str; //If n is not divisible by 2, then we append 1 at the beginning
}
n=n/2; //Updating value of n
}
return str; //Returning string with binary equivalent
}
static int count(String str) //Function to count number of "1"s in binary equivalent
{
int cnt=0; //Initializing count variable to zero
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='1')
{
cnt++; //If character is 1, increment value of cnt
}
}
return cnt; //Return the number of "1"s in the binary string
}
}
So,I am uploading the simplest logic of this program without using any loop.Just check and you will get the answer.
Answer:
public class Evil_Odious
{
public static void main(String[] args)
{
String a = String.valueOf(9);
int num = Integer.parseInt(a);
int num_convert = Integer.parseInt(Integer.toBinaryString(num));
System.out.println("Number=" + num);
System.out.println("Binary Form=" + num_convert);
String g = String.valueOf(num_convert);
System.out.println(g);
int i=g.length();
int math=(int) Math.pow(10,i);
int math_divide=math/10;
int minus_karo=num_convert-math_divide;
int divide_karo=num_convert/math_divide;
System.out.println("Minus karne ke baad="+minus_karo);
System.out.println("Divide karne ke baad="+divide_karo);
if ((minus_karo+divide_karo)%2==0)
{
System.out.println("Evil number");
}
else
{
System.out.println("Odious number");
}
}
}
Note:Please don't laugh at my variable names.I have written that, just for better understanding.
Note: If you want user input number, then you see the second method.
Logic:-
Scanner sc=new Scanner (System.in);
int a=sc.nextInt();
int b=Integer.parseInt(Integer.toBinaryString(a));
if(b%2==0)
System.out.println("Evil number");
else
System. out. println("Odious number");