题解 | #用rand5()实现rand7()#
用rand5()实现rand7()
http://www.nowcoder.com/practice/581fb9be10d647e7bb179234b42f3f5f
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* rand5() is defined
* @return a random integer in the range 1 to 7
*/
public int rand5() {
return 1 + (int) (Math.random() * 5);
}
public int rand7() {
// write code here
int ans = 0;
do {
ans = (rand01() << 2) + (rand01() << 1) + rand01();
} while (ans == 7);
return ans + 1;
}
public int rand01() {
int tmpValue = 0;
do {
tmpValue = rand5();
} while (tmpValue == 5);
return tmpValue % 2;
}
}