Subhash
Subhash

Reputation: 383

Bitwise operations in java

what does this piece of code mean ...Can anyone explain how does this work..

sum += (i & (1<<j)) != 0 ? n[j] : 0;

full code:

  int max = (1 << N)-1;

  //System.err.println(max);
  String res = "No";
  for (int i = 0; i <= max; i++)
  {
    long sum = 0;
    for (int j = 0; j < N; j++)
    {
      sum += (i & (1<<j)) != 0 ? n[j] : 0;
    }
    //System.err.println(i + " " + sum);
    if(sum == m){

      res = "Yes";
      break;
    }

Upvotes: 0

Views: 542

Answers (2)

N0D1R
N0D1R

Reputation: 313

With this code i & (1 << j) you get jth bit of i in binary representation. And if it equals 1 then you add n[j] to sum. The full code shows you calculate all possible sums with selecting some elememts of array n;

Upvotes: 2

Typo
Typo

Reputation: 1910

Let's say that a = 0011 1100

So with the Binary Left Shift Operator (<<). The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

So in your code you have a loop for i and a loop for j

And this line

sum += (i & (1<<j)) != 0 ? n[j] : 0;

So for your second iteration of i = 2 and first iteration of j = 1

First the left shift operator will shift left all bits one position, resulting in 0000 0001 << 1 = 0000 0010 (or 2)

then you have a binary and comparison which will be i (0000 0010 in binary) & (0000 0010) = 0000 0010 (or 2)

And this and result will be asked if it's distinct of zero. If this result it's true then sum will be increased by the number in the n[j] array position, else will not be increased.

Java has a shortened version of an if else command. The use of it is very easy, once you understand it.

It’s written:

x ? y : z;

Here the question mark and the colon will take the place of the commands if and else. This means:

condition ? inCaseOfTrue : elseCase;

Upvotes: 3

Related Questions