https://sites.google.com/site/codingbughunter/algorithm-question-discuss
You have a function rand1() to random generate number 0 or 1. Can you make a function to generate randN(int n)
给定rand1():能够产生random数字0,1 用rand1()实现: rand3()--> 0, 1, 2, 3 rand4()--> 0, 1, 2, 3, 4 randN(int n)--> 0, 1, ..., N n可以是任意整数,包括0、负整数、正整数 ,注意edge case
public int randomGenerateNum(int n){ int numOfDigits = 0; int booleanNum = (n<0 ? 1: 0); n = Math.abs(n); int tmp = n; while(tmp > 0){ numOfDigits++; tmp /= 2; } int res = 0; while(true){ for(int i = 0; i<numOfDigits; i++){ res = res*2+rand1(); } if(res <= n){ break; }else{ res = 0; } } return booleanNum == 0 ? res : -res; } private int rand1(){ // for test Random rn = new Random(); return rn.nextInt(2); }