Practice: bits and math
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Now combine bitmasks, XOR algebra, binary shifting, the Sieve of Eratosthenes, and Fermat's Little Theorem to solve the core bit-and-math problems asked in technical interviews.
Count Primes Up to n and Power Set with Bitmasks
Problem 1 — Count Primes Strictly Less Than n: Given 0 ≤ n ≤ 5 × 10⁶, return the number of primes strictly less than n (sample: n = 10 → 4 for 2, 3, 5, 7; n = 2 → 0).
Example 1 · Power Set Generation Using Bitmasks
import java.util.ArrayList;import java.util.List;
public class BitmaskPowerSetDemo { public static List<List<Integer>> subsets(int[] nums) { int n = nums.length; int total = 1 << n; List<List<Integer>> result = new ArrayList<>(total); for (int mask = 0; mask < total; mask++) { List<Integer> subset = new ArrayList<>(); for (int i = 0; i < n; i++) { if ((mask & (1 << i)) != 0) { subset.add(nums[i]); } } result.add(subset); } return result; }
public static void main(String[] args) { System.out.println("Subsets of [1, 2, 3]: " + subsets(new int[]{1, 2, 3})); }}Subsets of [1, 2, 3]: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
What this code does
maskranges from000_2(0, empty subset) to111_2(7, full subset[1, 2, 3]).- Complexity is O(n · 2ⁿ) time and O(1) extra working space.
Trial division takes O(n√n) and times out; a Sieve of Eratosthenes crosses out multiples from p² up to n - 1 in O(n log log n) time and O(n) space.
Problem 2 — Power Set with Bitmasks: Given an array nums of n distinct integers (1 ≤ n ≤ 10), return all 2ⁿ subsets (sample: [1, 2] -> [[], [1], [2], [1, 2]]). Each integer mask from 0 to (1 << n) - 1 is a binary codeword of length n: bit i is 1 ((mask & (1 << i)) != 0) if and only if nums[i] belongs to that subset. Generating all 2ⁿ subsets takes O(n · 2ⁿ) time and O(1) auxiliary space beyond the output list.
- Count Primes edge case: when n ≤ 2, there are
0primes strictly less than n. - Power Set size check: for n elements, the outer loop runs from
0to(1 << n) - 1, producing exactly 2ⁿ subsets.
Single Number II and Single Number III
Problem 3 — Single Number II: In nums (1 ≤ n ≤ 3 × 10⁴), every integer appears three times except one integer that appears once (sample: [2, 2, 3, 2] -> 3). Plain XOR fails because x ⊕ x ⊕ x = x.
- Hand trace of Single Number III on
[1, 2, 1, 3, 2, 5]: full XOR is3 ^ 5 = 6(0110_2). - Lowest set bit of
6:lowBit = 6 & -6 = 2(0010_2). - Numbers with bit
2unset (0):1, 1, 5-> XOR is5. - Numbers with bit
2set (1):2, 3, 2-> XOR is3. Result:[3, 5].
Example 2 · Single Number II (Bit Counting Mod 3) and Single Number III (Lowest Set Bit Split)
import java.util.Arrays;
public class SingleNumberVariantsDemo { public static int singleNumberII(int[] nums) { int ans = 0; for (int b = 0; b < 32; b++) { int bitSum = 0; for (int num : nums) { bitSum += (num >>> b) & 1; } if (bitSum % 3 != 0) { ans |= (1 << b); } } return ans; }
public static int[] singleNumberIII(int[] nums) { int diff = 0; for (int num : nums) { diff ^= num; } int lowBit = diff & -diff; int x = 0; int y = 0; for (int num : nums) { if ((num & lowBit) == 0) { x ^= num; } else { y ^= num; } } int[] res = {x, y}; Arrays.sort(res); return res; }
public static void main(String[] args) { System.out.println("Single Number II [2, 2, 3, 2]: " + singleNumberII(new int[]{2, 2, 3, 2})); System.out.println("Single Number II [-2, -2, -5, -2]: " + singleNumberII(new int[]{-2, -2, -5, -2})); System.out.println("Single Number III [1, 2, 1, 3, 2, 5]: " + Arrays.toString(singleNumberIII(new int[]{1, 2, 1, 3, 2, 5}))); }}Single Number II [2, 2, 3, 2]: 3 Single Number II [-2, -2, -5, -2]: -5 Single Number III [1, 2, 1, 3, 2, 5]: [3, 5]
What this code does
- In
singleNumberII, checking all 32 bits including bit 31 reconstructs negative two's complement numbers like-5without special sign handling. - In
singleNumberIII,lowBit = diff & -difffinds the lowest bit where the two unique numbers differ, splitting the array into two independent Single Number I instances.
Instead, examine each bit position b ∈ [0, 31] independently: every tripled number contributes either three 0s or three 1s to bit b, so the total count of 1s at bit b across the whole array modulo 3 is the exact b-th bit of the single number! Time: O(32n) = O(n), space: O(1).
Problem 4 — Single Number III: In nums (2 ≤ n ≤ 3 × 10⁴), every integer appears twice except two distinct integers x and y that appear once (sample: [1, 2, 1, 3, 2, 5] -> [3, 5]). First XOR all numbers to get diff = x ^ y. Since x ≠ y, diff != 0, so at least one bit is 1. Isolate the lowest set bit lowBit = diff & -diff where x and y differ (one has bit 1, the other has bit 0). Partition all elements of nums into two groups based on (num & lowBit) == 0; the duplicates still pair up inside the same group and cancel, leaving x in one XOR bucket and y in the other! Time: O(n), space: O(1).
Bitwise Integer Division and Modular nCr
*Problem 5 — Divide Two Integers Without /, `, or %:** Given 32-bit signed integers dividend and divisor (divisor != 0), return the truncated quotient clamped to [Integer.MIN_VALUE, Integer.MAX_VALUE] (sample: (10, 3) -> 3, (7, -3) -> -2, (-2147483648, -1) -> 2147483647`).
Example 3 · Brute force: divide by repeated subtraction (O(dividend / divisor) time, O(1) space)
public class DivideBySubtraction { public static int divide(int dividend, int divisor) { long a = Math.abs((long) dividend); long b = Math.abs((long) divisor); long quotient = 0; while (a >= b) { a -= b; quotient++; } if ((dividend < 0) ^ (divisor < 0)) { quotient = -quotient; } return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, quotient)); }
public static void main(String[] args) { System.out.println(divide(10, 3)); System.out.println(divide(7, -3)); System.out.println(divide(1_000_000, 7)); }}3 -2 142857
What this code does
- Subtracting the divisor until nothing is left counts the quotient one step at a time. 1 000 000 / 7 takes 142 857 steps.
- With a dividend near 2³¹ and a divisor of 1 it would need about two billion steps, so it times out.
Example 4 · Optimal: divide with bit shifts (O(log dividend) time, O(1) space)
public class BitwiseDivideDemo { public static int divide(int dividend, int divisor) { if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } boolean negative = (dividend < 0) ^ (divisor < 0); long a = Math.abs((long) dividend); long b = Math.abs((long) divisor); long quotient = 0; for (int shift = 31; shift >= 0; shift--) { if ((a >>> shift) >= b) { a -= (b << shift); quotient += (1L << shift); } } return negative ? (int) -quotient : (int) quotient; }
public static void main(String[] args) { System.out.println("divide(10, 3) = " + divide(10, 3)); System.out.println("divide(7, -3) = " + divide(7, -3)); System.out.println("divide(-2147483648, -1) = " + divide(Integer.MIN_VALUE, -1)); System.out.println("divide(-2147483648, 1) = " + divide(Integer.MIN_VALUE, 1)); }}divide(10, 3) = 3 divide(7, -3) = -2 divide(-2147483648, -1) = 2147483647 divide(-2147483648, 1) = -2147483648
What this code does
(dividend < 0) ^ (divisor < 0)uses boolean XOR to detect when the two operands have opposite signs.- Casting
(long) dividendbeforeMath.abspreventsMath.abs(Integer.MIN_VALUE)from overflowing. - It is faster because each step removes the divisor times a power of two, so 32 steps are enough for any int.
Repeated subtraction takes O(2³¹) steps and times out. Instead, convert to positive long values a = Math.abs((long) dividend) and b = Math.abs((long) divisor), and loop shift from 31 down to 0: whenever (a >> shift) >= b, subtract b << shift from a and add 1L << shift to the quotient. This binary long-division runs in 32 steps (O(log(dividend)) = O(1) time, O(1) space).
Problem 6 — nCr Modulo 10⁹ + 7: Given 0 ≤ r ≤ n ≤ 10⁵, compute C(n, r) mod 1 000 000 007 (sample: (10, 3) -> 120, (100, 50) -> 538992043). Precompute fact[0..n] in O(n) time and multiply fact[n] by the Fermat modular inverse of (fact[r] * fact[n - r]) % MOD in O(log MOD) time.
- Only one 32-bit division can overflow:
Integer.MIN_VALUE / -1 = +2_147_483_648, which exceedsInteger.MAX_VALUEby1. - Using
(a >> shift) >= binstead ofa >= (b << shift)preventsb << shiftfrom overflowing.
Finish up
Mark complete & continue
Next: Spotting the pattern