Professional Documents
Culture Documents
count bits in an integer. Solved using mask, did not attempt -1 approach.
E: count bits in an integer....
Monday, January 23, 2006 6:31 PM | Jack
Given x.
Although this is probably inefficient by the interviewer's stds, you could do th
is...
short numbits=0;
if(x<0)
numbits=1;
x <<= 1;
while(x!=0)
{
if(x<0)
numbits++;
x<<=1;
}
RE: count bits in an integer....
Monday, January 23, 2006 6:58 PM | Jack
One way to incorporate masking would be to group the bits into hex digit
s. Then, a hex digit has 0<= bits set<= 4.
RE: count bits in an integer....
Sunday, February 19, 2006 7:05 PM | Ajay
int MathC::countBits(unsigned int num){
int count=0;
while(num!=0){
count+=num & 1;
num=num>>1;
}
return count;
}
RE: count bits in an integer....
Wednesday, June 14, 2006 9:25 AM | Answer Dude
You can shorten the loop by using a lookup table and checking say 8 bits
at a time. I seem to remember something from discrete math that wouldn't requir
e a loop.. not sure though. Anyone know?
Given an array of integers where every int has exactly one duplicate except one,
find the number with odd occuring number.
Shouldn't { 2*n*(n+1)/2 - Array Sum } work
This was a hard problem until Khoa mentioned thinking about the numbers
on a binary level. Since each number XOR'ed by itself will clear it's set bits,
you can go through the array XORing each number and end up with the number witho
ut a pair.
Consider the example:
2,3,2,4,3
0010
0011
---0001
0010
---0011
0100
---0111
0011
---0100
//
//
//
//
//
//
//
//
//
//
//
//
//
2
3
XOR'ed
result
2
XOR'ed
result: 3 (the odd number so far)
4
XOR'ed
result
3
XOR'ed
result 4 (The odd number in the sequence)
Save the already picked somg in an array of BOOL that its indexes are the song n
umber. TRUE for picked song. that array will allow you to check whether the rand
om result song already picked or not
Copy the 4 to 3, and delete that node using the pointer pointing to 4 now (point
ing to 3 before)..
RE: You have a singly linked ...
Thursday, March 23, 2006 11:10 PM | yoyo
node* temp = list->next;
if(temp){
list->value = temp->value;
list->next = temp->next;
delete temp;
}
You have a singly linked list say 1->2->3->4->5 and you have no access to its he
ad pointer. But you have access to another pointer which points to the node 3. H
ow would you delete node 3 and get the output at 1->2->4->5. Remember its a sing
ly linked list