Friday, July 17, 2009

C# technical interview algorithm question: Print 32-bit Integers with only 7 bits on

In a recent interview, the engineer at the other side of the table asked me to write C# code that would print out all 32-bit Integers that have only 7 bits turned on. I don't consider this a great interview question, because it doesn't measure most things, yet it strongly measures your ability to write recursive method signatures. How many times have you ever had to write complex recursive methods in your last job? When I interview people, I ask them algorithm questions they're very likely to use.

In case you're wondering, I did pass, but my whiteboard code wasn't as clean as the following.

Nevertheless, here's the source-code just in case it helps anyone prepare for an interview. Do your own validation. It spits out the answer but it might not have certain memory optimizations that someone with a C++ background might look for. For one thing, I'm passing a lot of arguments by copying. If they do insist on optimizations and they only give you half an hour, you probably don't wanna work for them anyway:


using System;

namespace PracticeApps.PracticeConsoleApps
{
class IntegerWithSevenBitsOn
{
static void Main(string[] args)
{
PrintIntegersWithSevenBitsOn();
}

// Prints all Integers that have only 7 bits on
static public void PrintIntegersWithSevenBitsOn()
{
PrintIntegersWithSevenBitsOn(0, 32, 1, 7);
}

// Helper to Print all ints with given # bits on
// number: The number that is modified recursively
// remainingSpots: Unassigned bit count in number
// mask: Helps flip a certain bit on the number
// unusedOnBits: ON-bit count yet to be placed
static private void PrintIntegersWithSevenBitsOn(
uint number,
int remainingSpots,
uint mask,
int unusedOnBits)
{
// Base case: No spots left to fill
if (0 == remainingSpots)
{
Console.Out.WriteLine(
Convert.ToString(number, 2));
}
// Recursive case
else
{
// As many remaining spots as ON-bits?
// Then place all of them recursively.
if (remainingSpots == unusedOnBits)
{
PrintIntegersWithSevenBitsOn(
number | mask,
remainingSpots - 1,
mask << 1,
unusedOnBits - 1);
}
// More spots than available ON-bits
else
{
// Use a Zero for the current spot
PrintIntegersWithSevenBitsOn(
number,
remainingSpots - 1,
mask << 1,
unusedOnBits);

// If available, use an ON-bit
if (unusedOnBits > 0)
{
PrintIntegersWithSevenBitsOn(
number | mask,
remainingSpots - 1,
mask << 1,
unusedOnBits - 1);
}
}
}
}
}
}

No comments: