Cracking the coding interview, 4 edition 150 programming interview questions and solutions

Page 128

Solutions to Chapter 5 | Bit Manipulation 5.3

Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation.

pg 58

SOLUTION The Brute Force Approach: An easy approach is simply brute force: count the number of 1’s in n, and then increment (or decrement) until you find a number with the same number of 1’s. Easy - but not terribly interesting. Can we do something a bit more optimal? Yes! Number Properties Approach for Next Number Observations: »»

If we “turn on” a 0, we need to “turn off” a 1

»»

If we turn on a 0 at bit i and turn off a 1 at bit j, the number changes by 2^i - 2^j.

»»

If we want to get a bigger number with the same number of 1s and 0s, i must be bigger than j.

Solution: 1.

Traverse from right to left. Once we’ve passed a 1, turn on the next 0. We’ve now increased the number by 2^i. Yikes! Example: xxxxx011100 becomes xxxxx111100

2.

Turn off the one that’s just to the right side of that. We’re now bigger by 2^i - 2^(i-1) Example: xxxxx111100 becomes xxxxx101100

3.

Make the number as small as possible by rearranging all the 1s to be as far right as possible: Example: xxxxx101100 becomes xxxxx100011

To get the previous number, we do the reverse. 1.

Traverse from right to left. Once we’ve passed a zero, turn off the next 1. Example: xxxxx100011 becomes xxxxx000011.

2.

Turn on the 0 that is directly to the right. Example: xxxxx000011 becomes xxxxx010011.

3.

Make the number as big as possible by shifting all the ones as far to the left as possible. Example: xxxxx010011 becomes xxxxx011100 .

And now, for the code. Note the emphasis on pulling common code out into a reusable function. Your interviewer will look for “clean code” like this.

135

Cracking the Coding Interview | Concepts and Algorithms


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.