Google Interview Question
Software Engineer / DevelopersCountry: United Kingdom
Interview Type: Phone Interview
Good answer. Here are versions to set, clear and flip n-th bit of m:
int set_nth_bit(const int m, const int n)
{
return m | (1 << n);
}
int clear_nth_bit(const int m, const int n)
{
return m & ~(1 << n);
}
int flip_nth_bit(const int m, const int n)
{
return m ^ (1 << n);
}
int func1(int n, int m)
{
if ( (n>>(m-1)) % 2==0)
return (n | (1<<(m-1)));
else
return (n ^ (1<<(m-1)));
}
Sorry do you mind explaining your solution a bit. I dont really know how to use these shifting bits left right and stuff
shifting n right by m-1 bit will bring m-th bit at lease significant position.
If the resultant number is even then m-th bit is 0, OR with one will alter the bit. that in in the IF part.
else the resultant number is odd , XOR with 1 will alter the bit.
I would be lying if i said i really did understand that.. What resources can i use to learn bit manipulation in full? I mean books or online tuts
Ke solution is more perfect, I should have realized in both the cases XOR will work. no need to check even and odd..
One lil hint I can give about shifting left and right.. rest you can search on google.. I learned like that only..
in numbers Right shift by 3 ( n >> 3) mean dividing n by 2*2*2
in binary if n = 00100011 n>>3= 00000100
in numbers left shift by 3 ( n << 3) mean multiplying n by 2*2*2.
in binary if n = 00011000 n<<3= 11000000
What does that mean flip?
The code shows bit-wise xor. I hate the question that are in-explicit and fuzzy.
Left shifting integer 1 (n-1) bits then xor it with the target.
- Ke February 09, 2012int FlipBit (int m, int n) {
return m ^ (1 << n - 1);
}