Microsoft Interview Question

Write a for loop, which prints the odd numbers from 0 to N.

Interview Answer

Anonymous

Nov 25, 2014

This looked like a really simple question, but the interviewer was expecting an specific answer. After several (correct) attempts, he said if it wouldn't be more efficient doing a bitwise test. So my final code was like this. for(size_t i = 0; i < N; ++i) { // Left shift to have the LSB set, test it against "i". // If true, it is an odd number if(i & (0 << 1)) { cout << i << " "; } } I don't see it as necessarily much more efficient. The modulo operation would have been ok, even though a division needs to be done. We gain minimum performance, but we lose simplicity in the code. I pointed this out to the interviewer.