emschorsch
emschorsch

Reputation: 1669

Explanation for a line of code in c++ related to bitshifts

I don't want someone to explain how the following code works (it checks whether an int is pandigital) as I should be doing that myself. I just need help understanding line 8 specifically. I don't know what the | is doing.

private bool isPandigital(long n) {
    int digits = 0;
    int count = 0;
    int tmp;

    while (n > 0) {
        tmp = digits;
        digits = digits | 1 << (int)((n % 10) - 1);
        if (tmp == digits) {
            return false;
        }

        count++;
        n /= 10;
    }
    return digits == (1 << count) - 1;
}

Upvotes: 3

Views: 218

Answers (5)

Scott Rippey
Scott Rippey

Reputation: 15810

I know others have already explained that it's a bitwise OR, but I'd like to give my own interpretation.

digits = digits | X will copy all the 1 bits from X into digits.

digits = digits | 1 << Y will "set" a single bit in digits - it will set the Yth bit.

So, each loop sets a bit in digits.

Upvotes: 1

zvrba
zvrba

Reputation: 24546

| is bitwise or. But the code checks whether an int of length n has all digits 1..n. This is different from palindrome check. That line sets's (i-1)'th bit of digits to 1 if the last digit of n is i. [BTW, the code is wrong: if n contains a zero-digit, that line will trigger "undefined behavior": shifting an integer by a negative amount gives an undefined result.]

The code uses an integer digits to represent a set of digits. You can learn more about the technique by searching for bit sets.

Upvotes: 1

Vinayak Garg
Vinayak Garg

Reputation: 6616

| is a bitwise or.

So the line is doing digits = digits | (1 << (int)((n % 10) - 1));

Upvotes: 0

Brian Roach
Brian Roach

Reputation: 76908

| is a bitwise OR

A bitwise OR takes two bit patterns of equal length and performs the logical inclusive OR operation on each pair of corresponding bits. The result in each position is 1 if the first bit is 1 OR the second bit is 1 OR both bits are 1; otherwise, the result is 0.

Example:

10010000
01010000
--------
11010000

http://en.wikipedia.org/wiki/Bitwise_operation

Upvotes: 0

user978122
user978122

Reputation: 5761

It appears to be performing a Bitwise Or.

Upvotes: 0

Related Questions