1
#include <iostream>
using namespace std;

bool klsb(int num, int k) {
    return (num & (1<<(k-1)));
}

int main() {
    int t;
    scanf("%d",&t);
    while(t--) {
        int num,k;
        scanf("%d%d",&num, &k);
        cout<< klsb(num,k)<< endl;
    }
}

In the above code, what does

return (num & (1<<(k-1)));

mean?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 3
    Have you learned about the `&` bitwise AND operator and the `<<` bitwise shift-left operator yet? If not, I suggest you get yourself a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Basically, `klsb()` is returning true or false depending on whether a specified bit in `num` is set to 1 or 0. – Remy Lebeau Oct 23 '19 at 18:48
  • @NathanOliver There should be a medal I could nominate you for that edit. I gave up immediately. – François Andrieux Oct 23 '19 at 18:50
  • @FrançoisAndrieux Thanks. Wasn't too bad. I've got a user script that lets me highlight a code block and then press tab to indent it all. Comes in really useful. – NathanOliver Oct 23 '19 at 18:51
  • 1
    It is [ill advised](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) to put `using namespace std` in your code. If you absolutely must save source code characters, limit the scope of the statement to something like `using std::cout` – loaner9 Oct 23 '19 at 19:10

2 Answers2

2

a & b is bitwise AND. The result will be a number where all bits that are 1 in a and b will be one and all other bits will be zero. Eg 101 & 110 = 100

a << b is binary shift left. It will take the bits of a and shift them to the left by b positions filling with zeros from the right and discarding the overflow. Eg 1011 << 1 = 0110

The statement in your code will create a number where bit k-1 is set (1 << (k-1)) and then AND it with num. The result is a number != 0 iff bit k-1 is set in num. This will then be casted to bool. Since any value != 0 is boolean true in C++ this function tests wether or not bit k-1 is 1 in num

ACB
  • 1,607
  • 11
  • 31
0

You use & as a bitwise AND, 1 << k-1 means that 1 is bit-shifted to the left by the amount of k-1:

$a & $b
And: Bits that are set in both $a and $b are set.

$a << $b
Shift left: Shift the bits of $a $b steps to the left (each step means "multiply by two")

Example:

1001 & 1000 = 1000 (the first 1 is in both)

11001<<2 = 1100100 (shifted 2 to the left)

Strohhut
  • 490
  • 1
  • 6
  • 22