HCL Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
I may be misunderstanding something here, and if I am please disregard, but it seems like this solution is almost correct. Let's keep with the question in the sense that they hypothetically want to toggle bits 11-15, it appears that this solution will only toggle bits 11-14.
I think
((1 << last) - 1)
should be slightly altered to
((1 << (last + 1)) - 1)
As an example, let's take the number: 85499444
[represented in binary as 0000 0101 0001 1000 1001 1110 0011 0100]
Assuming
last = 15
and
first = 11
.
With the original solution of:
size_t mask = ((1 << last) - 1) ^ ((1 << first) - 1);
We get a mask of
0000 0000 0000 0000 0111 1000 0000 0000
As we can see this only has an effect on bits 11-14.
However, with the slight alteration of:
size_t mask = ((1 << (last + 1)) - 1) ^ ((1 << first) - 1);
We get a mask of
0000 0000 0000 0000 1111 1000 0000 0000
Which we can see has an effect on bits 11-15.
That said
0000 0101 0001 1000 1001 1110 0011 0100 ^
0000 0000 0000 0000 1111 1000 0000 0000
==================================
0000 0101 0001 1000 0110 0110 0011 0100
This effectively toggles bits 11-15 of the number 85499444.
TL;DR
Unless I misunderstood, I think the correct solution is actually:
size_t toggleBits(size_t num, size_t first, size_t last) {
size_t mask = ((1 << (last + 1)) - 1) ^ ((1 << first) - 1);
return num ^ mask;
}
If you want to toggle a bit, just XOR it with 1 since 0 ^ 1 = 1; 1 ^ 1 = 0.
- LinhHA05 July 31, 2013