The Evil number is another special positive whole number in Java that has an even number of 1's in its binary equivalent. Unlike Prime and Armstrong numbers, Evil number is not so popular and asked by the interviewers.
The numbers which are not evil are called odious numbers. Let's some examples of evil and odious numbers.
- 15 is an evil number because in its binary equivalent, i.e., 1111, it has an even number of ones.
- 16 is an odious number because in its binary equivalent, i.e., 10000 has not even number of ones
- 23 is also an evil number because it has an even number of ones in its binary equivalent, i.e., 10111.
In order to check whether the number is evil or not, we have to follow the following steps:
- We first take a number.
- We then find the binary equivalent of this number and store it into another variable.
- We find the total number of ones in the binary number.
- If we found an even number of ones in the binary equivalent number, then the number is an evil number. Else the given number is not an evil number.
Note: To convert a decimal number into binary, we can use the toBinaryString() in-built method or do it manually by using the loop.
EvilNumberExample.java
Output
Let's implement one more program to get all the Evil numbers in a given range
FindAllEvilNumber.java
Output
need an explanation for this answer? contact us directly to get an explanation for this answer