-2

I'm preparing for a programming contest and I have stumbled upon the question below.

void main(){
    int number, result;
    scanf("%d",&number);
    result=number-(number&-number); //this is what i'm struggling to understand
    printf("%d",result);  
}

Note the use of "&-" in the commented line. I couldn't figure out its function. I tried googling and reverse engineering but I couldn't find anything.

Also, the question itself is not about the exact output because the variable "number" is dynamic. I just need to learn what the "&-" part do. Thanks!

3 Answers3

6

This is a binary AND operator. The expression x & -x zeroes out all but the rightmost 1-bit in the number x. Then x - (x & -x) zeroes only that bit, so the result is the original number with the rightmost 1-bit cleared.

Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
1

The ampersand is a binary AND operator. The minus is just a regular minus. Thanks to @tkausl

0

(number&-number) means (number & (-number))

Kamil
  • 3
  • 4