Wap to enter a number and check if it is a evil number or not
Using java and function parameter
Please give the definition of evil number
Urgent
Answers
Definition of Evil Number:
- A number is said to be an evil number only if it's binary expansion is containing "even" number of 1's in it.
Program:
import java.util.Scanner;
import java.lang.Integer.*;
public class Main{
public static void main(String[] args) {
System.out.println("Enter a number to check weather it is evil number or not");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
String binary = Integer.toBinaryString(number);
int evil=0;
for(int i = 0 ; i < binary.length() ; i++){
if(binary. charAt(i) == '1'){
evil = evil + 1;
}
}
if(evil % 2 == 0 && evil > 0){
System.out.println("Number"+number+" is an evil number");
}else{
System.out.println("Number "+number+" is not an evil number");
}
}
}
Output-1:
Enter a number to check weather it is evil number or not : 23
Number 23 is an evil number
Output-1:
Enter a number to check weather it is evil number or not : 19
Number 19 is not an evil number
Explanation:
- In java there is predefined method called toBinaryString() where it takes the given integer and returns the binary expansion of that integer
- so i used it to first convert the given number into binary format and stored it as a string variable "binary".
- and then using for loop i took each character from the number using predefined method charAt() which takes index of the character you want in the given string as an argument and returns that character so i used it to get the every character from that string and checked if it is 1 or not
- if true then i increased the value of variable "evil" to 1
- it not the loop iterates until end of the string length condition gets false
- at last i will get the value of number of 1's in the number and i will check if it is even or not
- if true then it is a evil number
- if not then it is not a evil number.
-- hop you liked my program and my definition of evil number and my explanation, if you liked it mark as brainliest.