Chapter 18 - Bit Manipulation

A few operators on bits replace loops, sets and extra memory.

Coding Interview Patterns book cover with the Rust logo and a CHAP 18 label, the chapter on bit manipulation

This page is the entry point of chapter 18 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.

The idea

Bit tricks rely on a handful of identities. x & (x - 1) clears the lowest set bit. x ^ x is zero, so XOR-ing every number of an array leaves only the one that appears once. Masks such as 0x5555_5555 select the even bits, 0xAAAA_AAAA the odd ones, and shifts move them into place.

The chapter also has an introduction page with my notes on the key ideas and a checklist.

When to reach for it

  • Counting set bits, parity, powers of two.
  • Finding the element that appears once among pairs.
  • Swapping, reversing or extracting bits.

In Rust

  • count_ones, leading_zeros and trailing_zeros are built into every integer type.
  • Work on unsigned types (u32): shifts and masks on signed values are a trap.
  • Shifting by the width of the type or more panics in debug builds: 1u32 << 32 is an error, not zero.

Problems in this chapter

  • p393 - Introduction: Introduction to the Bit Manipulation pattern for coding interviews, in Rust: the key idea, when to use it, and the problems of the chapter.
  • p396 - Hamming Weights of Integer: Hamming Weights of Integers (Bit Manipulation) solved in Rust: count the bits set to 1 in every integer from 0 to n.
  • p399 - Lonely Integer: Lonely Integer (Bit Manipulation), solved in Rust. Given an integer array where each number occurs twice except for one, find the unique (to rule them all?).
  • p401 - Swap Odd and Even Bits: Swap Odd and Even Bits (Bit Manipulation) solved in Rust: swap every bit in an even position of a u32 with its adjacent odd bit.

Other chapters

All the chapters, with every problem, are listed on the series page.


Back to top

Published on: Dec 1 2026 at 10:00 AM | Last updated: Dec 1 2026 at 10:32 AM

Copyright © 1964-2026 - 40tude