Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Bonsai Boy of New York Bonsai Trees and Accessories

BlueHost Web Hosting

Liquid Web iThemes WordPress Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Liquid Web Cloud VPS Hosting

10,567 questions

14,363 answers

573 users

How to check if a number has same number of set and unset bits in Java

1 Answer

0 votes
import java.io.*;  
   
public class MyClass {
    static boolean check_same_set_and_unset_bits(int n) { 
        int set = 0, unset = 0; 
    
        while (n != 0) { 
            if ((n & 1) == 1) 
                set++; 
            else
                unset++; 
            n = n >> 1; 
        } 
        
        if (set == unset) 
            return true; 
        
        return false; 
    }  
    public static void main(String args[]) {
        int n = 178;
  
        System.out.println(Integer.toBinaryString(n)); 
 
        if (check_same_set_and_unset_bits(n)) 
            System.out.println("Yes\n"); 
        else
            System.out.println("No\n"); 
            
        n = 179;
  
        System.out.println(Integer.toBinaryString(n)); 
 
        if (check_same_set_and_unset_bits(n)) 
            System.out.println("Yes\n"); 
        else
            System.out.println("No\n"); 
    }
}
   

   
/*
run:
   
10110010
Yes

10110011
No
  
*/

 




answered Mar 11 by avibootz
edited Mar 11 by avibootz
...