Implement a random function


  • 0
    P

    Write a function to generate random numbers between given range (5 to 55 inclusive) using a given function "rand_0()" which returns whether '0' or '1'.


  • 1
    P
    public static int myRand() {
    		
    		StringJoiner s = new StringJoiner("");
    		while(true) {
    			if(s.length() < 8) {
    				s.add(String.valueOf(rand_0()));
    				continue;
    			}
    				
    			int v = Integer.parseInt(s.toString(), 2);
    			
    			if(v >= 5 && v<=55) {
    				return v;
    			} else {
    				s = new StringJoiner("");
    			}
    		}
    	}
    
    

  • 0
    J
    def my_random():
        return 50*rand() + 5
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.