Evil Number
A number which when converted to binary format has an even number of 1’s is an Evil number. An example of such number is 12.
Binary equivalent of 12 is 1100. Number of 1’s = 2, an even number.
Method 1 : By converting the number to binary
This method first converts the given number to its binary equivalent. This binary number is then iterated and its digits are compared with 1.
If the digit is a 1, a count variable initialized at the beginning is incremented. This count variable represents the count of 1s in the binary number.
Finally this count is divided by 2 to check if it is even or not.
static void methodOne() {
int number = 12;
// convert the number to a binary number. Result :: 1100
String numStr = Integer.toBinaryString(number);
// initialize count of 1's in the number
int numberOfOnes = 0;
// iterate over the digits of binary number
for (int i = 0; i < numStr.length(); i++) {
// increment count if the digit is a 1
if (numStr.charAt(i) == '1') {
++numberOfOnes;
}
}
// divide the count of 1s by 2 to check if its even
if (numberOfOnes % 2 == 0) {
System.out.println("Number is evil");
} else {
System.out.println("Number is not evil");
}
}
This approach is similar to the above method but the number is not straight away converted to binary. Instead, the number is iterated and in every iteration, the number is divided by to get the remainder.
The remainder is checked to be 1 and a count variable is incremented if the remainder is 1.
Also the number if divided by 2 to get the quotient and the quotient is re-assigned to the number so that it is reduced in every iteration.
static void methodTwo() {
int number = 12;
// initialize count of 1's in the number
int numberOfOnes = 0;
while (number > 0) {
//get the remainder after division of number by 2
int remainder = number % 2;
// increment count if the digit is a 1
if (remainder == 1) {
++numberOfOnes;
}
//get the quotient after division by 2 and assign it back to the number
number = number / 2;
}
// divide the count of 1s by 2 to check if its even
if (numberOfOnes % 2 == 0) {
System.out.println("Number is evil");
} else {
System.out.println("Number is not evil");
}
}
Note : In the above approaches, the number has been initialized in the methods. These methods can be modified to accept the number to be tested as user input or from console.
Check this out to know different methods of reading input from console.