Amazon.com Interview Question
1,578 Interview Reviews |
Back to all Amazon.com Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Senior Software Engineer at Amazon.com:
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (4)
1 of 1 people found this helpful
int RandBin()
{
int rand5Res = Rand5();
return rand5Res < 2 ? 0 : rand5Res < 4 ? 1 : RandBin();
}
And then use RandBin() to implement Rand7;
int Rand7()
{
int rand = RandBin() << 2 | RandBin() << 1 | RandBin();
return rand < 7 ? rand : Rand7();
}
Helpful Answer?
Yes |
No
Inappropriate?
{
while(1)
{
int n = ((rand5()%2)*4 + (rand5()%2)*2 + (rand5()%2)*1);
if(n == 0)
continue;
return n;
}
}
The rand5()%2 will generate 0 and 1 with equal probability and we need 3 bits since we are going from 000 upto 111. So we call this function thrice for each bit position.
Helpful Answer?
Yes |
No
Inappropriate?
int rand7()
{
while(1)
{
int n = ((rand5()%2)*4 + (rand5()%2)*2 + (rand5()%2)*1;
if(n==0)
continue;
return n-1;
}
}
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up



0 of 0 people found this helpful
by David:
int RandBin()
{
}