Amazon Interview Question
Software EngineersCountry: United States
public static boolean evenParity(Integer value){
int i =0;
boolean result = false;
do{
if ((value&1) == 1){
i++;
}
value = value>>1;
}while(value == 0);
if(i % 2 == 0){
result = true;
}
return result;
}
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int parity(int n, int bits, int p) {
return (bits == 0) ? p : parity(n, bits - 1, (n & (1 << (bits-1))) ? ((p + 1) % 2) : p);
}
int main(int argc, char**argv) {
int n = 0;
sscanf(argv[1], "%d", &n);
int bits = floor(log(n)/log(2)) + 1;
int p = parity(n, bits, 0);
printf("%d", p);
return 0;
}
I am a newbe, I have a basic question here. We need to count the number of ones and if they are odd, then its odd or even parity bit. Now, when we look at the code, the code keeps right shifting the number until it reaches '0'. So, we are counting bits from different number than the one passed.My, understanding was we should count the one bits of a given number without chaining the number. Even though this code is working correctly I'm not able to understand how this is working.
- Dave H March 18, 2015