# How to Calculate an Evil No in java

0
143
• 1
•
•
•
•
•
•
•
•
•
1
Share How to Calculate an Evil No in java

### Evil No-Definition

A number N will be evil number if it has an even number of 1’s in it’s binary expansion.

### Logic

1. Get the number from user.
2. Find binary form of the number
3. The binary stream will be an String of 1s and 0s.
4. Now create a counter and initialize it to 0(to satisfy the input for 0. binary of decimal 0 is also zero).
5. Convert the String to array.
6. Check the array element one by one for 1.
7. if 1 found increment the counter by one
8. check the number of 1s are even or odd.
9. If it is found even….you are done that is the Evil number.

### Lets code

for
1. Get the number from user.   check here
2. Find binary form of the number…check here
3. The code looks like-

``````

public class HelloWorld{

public static void main(String []args){
checkEvil("13");
}

public static void checkEvil(String input)
{
//declare the counter and initialize it to 0
int counter=0;
int len=input.length();
//Scan through the binary stream for 1
for(int i=0;i<len;i++)
{
if (input.charAt(i)=='1')
{
//if an one found increment counter by 1
counter++;
}
}
// Check the odd even logic
if((counter%2)==1) {
System.out.println("not evil");
}
else
System.out.println("evil");
}
}

``````

The output of the code:
\$javac HelloWorld.java
\$java -Xmx128M -Xms16M HelloWorld
not evil

Don't miss out!

Receive top technical news, lesson ideas, travel tips and more!

Give it a try. You can unsubscribe at any time.