|
| 1 | +import Java.util.*; |
| 2 | +import java.io.*; |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +//create EvilNumberExample class to check whether the given number is an Evil number or not |
| 6 | +public class EvilNumberExample { |
| 7 | + |
| 8 | + // create checkNumber() method that returns true when it founds number Evil |
| 9 | + public static boolean checkNumber(int n) { |
| 10 | + |
| 11 | + // find the equivalence binary number using user defined convertToBinary() method |
| 12 | + long binaryNumber = convertToBinary(n); |
| 13 | + |
| 14 | + // find total number of 1's in binary number |
| 15 | + int count = 0; |
| 16 | + |
| 17 | + // iterate each digit of binary number |
| 18 | + while(binaryNumber != 0) { |
| 19 | + |
| 20 | + // if the last digit of binary number is 1, increase the count value |
| 21 | + if(binaryNumber % 10 == 1) |
| 22 | + count++; |
| 23 | + |
| 24 | + // remove the last digit from the number |
| 25 | + binaryNumber = binaryNumber / 10; |
| 26 | + } |
| 27 | + |
| 28 | + // check whether the value of count is even or odd |
| 29 | + if(count % 2 == 0) |
| 30 | + return true; //return true when the value of count is even |
| 31 | + |
| 32 | + //return false if the value of the count is false |
| 33 | + return false; |
| 34 | + } |
| 35 | + |
| 36 | + //create convertToBinary() method to convert the decimal value into binary |
| 37 | + private static long convertToBinary(int number) { |
| 38 | + long binaryNumber = 0; |
| 39 | + int rem = 0; |
| 40 | + int j = 1; |
| 41 | + while(number != 0) { |
| 42 | + rem = number % 2; |
| 43 | + binaryNumber += rem * j; |
| 44 | + number = number / 2; |
| 45 | + j = j * 10; |
| 46 | + } |
| 47 | + |
| 48 | + return binaryNumber; //return the binary equivalent number of the decimal number |
| 49 | + } |
| 50 | + |
| 51 | + //main() method start |
| 52 | + public static void main(String[] args) { |
| 53 | + |
| 54 | + // declare variable in which the user entered value will be store |
| 55 | + int num = 0; |
| 56 | + |
| 57 | + // create scanner class object |
| 58 | + Scanner sc = new Scanner(System.in); |
| 59 | + |
| 60 | + //display custom message |
| 61 | + System.out.print("Enter a number : "); |
| 62 | + |
| 63 | + //get input from user |
| 64 | + num = sc.nextInt(); |
| 65 | + |
| 66 | + // check whether the number is evil number or not |
| 67 | + if(checkNumber(num)) |
| 68 | + System.out.println(num + " is an evil number"); |
| 69 | + else |
| 70 | + System.out.println(num + " is not an evil number"); |
| 71 | + |
| 72 | + } |
| 73 | +} |
0 commit comments