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;
}
I know others have already explained that it’s a bitwise OR, but I’d like to give my own interpretation.
digits = digits | Xwill copy all the 1 bits from X into digits.digits = digits | 1 << Ywill “set” a single bit in digits – it will set the Yth bit.So, each loop sets a bit in digits.