Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to check if a number is evil number (binary representation contains even number of 1) in Java

1 Answer

0 votes
// Evil number = positive whole number whose binary representation contains an even number of 1's

public class MyClass {
    public static int countNumberOfOne(String binaryNumber) {
        int length = binaryNumber.length();

        int count = 0;
        char ch;
        
        for (int i = 0; i < length; i++) {
            ch = binaryNumber.charAt(i);
            if (ch == '1')
                count++;
        }
        
        return count;
    }
    
    public static boolean checkEvilNumber(Integer number) {
        String binaryNumber =  Integer.toBinaryString(number);
        
        System.out.print(number + " = " + binaryNumber + " = ");
        
        return (countNumberOfOne(binaryNumber) % 2 == 0) ? true : false;
    }

    public static void main(String args[]) {
        Integer number = 23;
        System.out.println(checkEvilNumber(number));
        
        number = 9863;
        System.out.println(checkEvilNumber(number));
    }
}
   
   
   
   
/*
run:
   
23 = 10111 = true
9863 = 10011010000111 = false
  
*/

 



answered Nov 24, 2023 by avibootz
edited Nov 25, 2023 by avibootz
...