0

here is the code and it returns "IGNORE HIM!" when the size is odd

#include <set>
std::set<char> s;
int main(){
    char c;
    while(std::cin>>c)s.insert(c);
    std::cout<<(s.size()&1?"IGNORE HIM!":"CHAT WITH HER!");
    return 0;
}
  • returns whether last bit is set to 1. – srt1104 Jul 22 '20 at 18:43
  • 2
    To have any hope of learning C++ in a reasonable amount of time you're going to have to [get and read a book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). The operators, what they do and how to use them will be covered in the early chapters. – user4581301 Jul 22 '20 at 18:45

3 Answers3

2

You've already noticed the pattern, i.e. set.size()&1 is true when the size is odd.

Doing a bitwise-and (&) on a number will set all the bits to 0, except for the last bit, if it's 1. The last bit is only 1 when the number is odd.

e.g.

  101100  // even
& 000001
= 000000  // false


  101101  // odd
& 000001
= 000001  // true
cigien
  • 57,834
  • 11
  • 73
  • 112
1

i & 1 is the same as i % 2 != 0, so it's checking if the number is odd, but in an obfuscated way. Don't do that. Your compiler knows how to optimize such things already.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • 1
    Why do you call it "obfuscated"? IMHO `i & 1` is just as clear as `i % 2 != 0`, if not more, and it is also nice and short. – Jesper Juhl Jul 22 '20 at 19:07
  • @JesperJuhl it maybe clear for you, but not for everyone, including OP. If it were just as clear, we wouldn't have this question, would we? – Aykhan Hagverdili Jul 22 '20 at 19:13
  • 3
    Neither is clear if you don't know what the `&` and `%` operators do. Once you know what those operators do I believe they are equally clear. I'll bet the next question from OP will be "what does the `%` operator do in C++". – Jesper Juhl Jul 22 '20 at 19:16
1

That is not a language nor container specific operation.
That is a typical operation to know if an integer is ODD or EVEN, performing the bitwise and operation for the bit 1 will only be true in ODD integers.

int odd=3; //binary 011
int even=4; //binary 100

if (odd&1)
   printf ("odd number");
if (!(even&1))
   printf ("even number");
Pablo Yaggi
  • 1,061
  • 5
  • 14