Java Number Programs (ISC Classes 11 / 12)
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
Java
Java Iterative Stmts
74 Likes
Answer
import java.util.Scanner;
public class KboatEvilNumber
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive number: ");
int n = in.nextInt();
if (n < 0) {
System.out.println("Invalid Input");
return;
}
int count = 0;
int p = 0;
int binNum = 0;
while (n > 0) {
int d = n % 2;
if (d == 1)
count++;
binNum += (int)(d * Math.pow(10, p));
p++;
n /= 2;
}
System.out.println("Binary Equivalent: " + binNum);
System.out.println("No. of 1's: " + count);
if (count % 2 == 0)
System.out.println("Output: Evil Number");
else
System.out.println("Output: Not an Evil Number");
}
}
Output
Answered By
24 Likes