Need help to solve DSA : Find position of set bit in java

44 views Asked by At
class Solution {
    static int findPosition(int N) {
        if((N&(N-1)) != 0) return -1;
        
        int pos = 1;
        while(N!=0){
            if((N&1) == 1){
                return pos;
            } else {
                pos++;
                N>>=1;
            }
        }
        return -1;    }
};

In this code, if the N is 5, then in while loop, (5&1) == 1 which satisfy the condition and it suppose to return 1, but the code is returning -1. Please explain where exactly I'm missing the concept

2

There are 2 answers

1
adityakale On BEST ANSWER
if((N&(N-1)) != 0) return -1;

Here it checks wether the value is power of 2 or not and 5 is not a power of 2 thats why it returns -1

0
Svetlin Zarev On

It's much easier to move the 1 bit than to shift the number. Also bit positions are counted from 0 instead of 1:

class Solution {
    static int findPosition(int N) {
      if((N & (N-1)) != 0) {
        return -1;
      }
      
      for(int i = 0; i < 32; i++){
        if ((N & (1 << i)) != 0){
          return i;
        }
      }

      return -1;    
    }
}

if the N is 5, then in while loop, (5&1) == 1 which satisfy the condition and it suppose to return 1, but the code is returning -1

This is caused by your first check:

if((N&(N-1)) != 0) return -1;

This code checks that your number has only one bit set to 1, but the number 5 in binary is 0b101 which has two bits set to 1. That's why you never reach your while loop:

5: 0b101
   AND
4: 0b100
--
   0b100 != 0

PS: There is another clever way to get that position:

class Solution {
    static int findPosition(int N) {
      var pos = Integer.numberOfTrailingZeros(N);
      return pos != 32 ? pos : -1;
    }
}