简体   繁体   中英

Java: How to do bitwise multiplication?

I am learning to generate all Subsets of a set, and try to convert the following C program

#include <stdio.h>
#include <math.h>

void printPowerSet(char *set, int set_size)
{
    /*set_size of power set of a set with set_size
      n is (2**n -1)*/
    unsigned int pow_set_size = pow(2, set_size);
    int counter, j;

    /*Run from counter 000..0 to 111..1*/
    for(counter = 0; counter < pow_set_size; counter++)
    {
      for(j = 0; j < set_size; j++)
       {
          /* Check if jth bit in the counter is set
             If set then pront jth element from set */
          if(counter & (1<<j))
            printf("%c", set[j]);
       }
       printf("\n");
    }
}

/*Driver program to test printPowerSet*/
int main()
{
    char set[] = {'a','b','c'};
    printPowerSet(set, 3);

    getchar();
    return 0;
}

Reference: http://www.geeksforgeeks.org/power-set/

My code looks like

private static void printAllSubsets(final Set<Integer> set) {
        final int subsetSize = (int) Math.pow(2, set.size());
        for (int counter = 0; counter< subsetSize; counter++) {
            for (int i = 0; i<set.size(); i++) {
                if(counter & (1 << i)) {

                }
            }
        }
    }

but I get compilation error on

if(counter & (1 << i)) 

as Required boolean Found int

How can I achieve the same result as in C code here? I do not understand how bitwise operations are going on here

Thanks

You can use

if ((counter & (1 << i)) != 0)

Java expects explicit boolean expressions in if conditions. In C, the != 0 is implicit.

As an aside, note that you can use

final int subsetSize = (1 << set.size());

instead of using Math.pow and casting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM