Cisco Systems Interview Question
Software Engineer / DevelopersTeam: Switching Softwares
Country: United States
Interview Type: Phone Interview
Since index is starting from 1.
int set_bits_range(int start, int end)
{
return ( (1 << (end - start + 1)) - 1 ) << (start-1);
}
What about the below code, please give feedback
int setbits(int start, int end) {
int no = 0;
int i;
for(i = start -1 ; i <= end - 1; i++) {
no |= (1 << i);
}
return no;
}
Set the range of bits from #L (least) to #H(highest)
1. Set the bit #(H-L+1)
2. Subtract 1 from the result
3. Shift the result by L bits to right
Just omitting the corner case checks to make the code clean.
- ashot madatyan May 07, 2012