Assume 0
-based indexing, we can shift n
too instead of 1
in the following tricks.
i
th bit: n | (1 << i)
i
th bit: n & ~(1 << i)
i
th bit, check if i
th bit is set or unset: if n & (1 << i) > 0
then set, else unseti
th bit: n ^ (1 << i)
n & (n - 1)
n | (n + 1)
n & ~(n - 1)
if(n & 1)
then odd, else evenn & (n - 1)
will be 0 (falsely reports 0
as a power of 2). Use this instead: if (n && !(n & (n - 1)) == 0)
x = x ^ y; y = x ^ y; x = x ^ y;
str[i] ^= 32
n & (d-1)
, so in place of (n % 4) we can write (n & 3).(x ^ y) < 0
a ^ b = 0 only if a, b are equal
number of set bits in A ^ B
.2x + x + x/2
= (x << 1) + x + (x >> 1)
8x - x
= (x << 3) - x
+
operator: xPlusOne = -(~x)
, since ~x = -(x+1)
holds.single set bit having even number of 0s on its right side
Do 2's complement, & with original number, take log2(ANDresult)
= log2(n & -n) + 1
(x | y) & (~x | ~y)
n % 4
values can be n, 1, n+1, 0
]n << k | n >> (32-k)
and Right = n >> k | n << (32-k)
Operations on Range:
ans = [L - R] = [1 - R] ^ [1 - (L-1)]
O(n)
, TLE on LC0
(shift out and shift back replacing it with 0s). TC = O(log n)
n & (n-1)
and this unsets the rightmost set bit and then AND operation on this position with any other number will yield 0
at this position in the final answer, so we keep doing this to form ans till ans > left
(in the last iteration ans & left
will happen as left = ans-1
). TC = O(popcount(n))
Forming two buckets trick:
Counting Bits trick: usually we can count set bits in log n
time using Brian-Kernighan’s Algorithm, but if we need to count set bits for each number in range [0 - n]
we can do so in O(n)
time using DP as dp[i] = dp[i/2] + i%2
where dp[0] = 0
is the base case problem video
N
shifting it rightwards by 1 (dividing by 2; halving) will either have equal set bits (if N
is even) or 1 extra set bits (if N
is odd) since shifting causes LSB to get lostEverything we do on a binary representation of a number is log n
time, since a number’s binary representation can contain atmost n
bits.