mardi 17 mai 2016

Generate a random integer with a specified number of digits Java [duplicate]

This question already has an answer here:

I ran into this problem today and I'm sure there is an elegant solution I am not thinking of.

Let's say I want to generate a random integer(or long) in Java with a specified number of digits, where this number of digits can change.

I.e. pass in a number of digits into a method, and return a random number with the specified number of digits

Ex.) N = 3, generate a random number between 100-999; N = 4, generate a random number between 1000-9999

private long generateRandomNumber(int n){

/*Generate a random number with n number of digits*/

}

My attempt so far (this works, but it seems messy)

private long generateRandomNumber(int n){

    String randomNumString = "";

    Random r = new Random();

    //Generate the first digit from 1-9
    randomNumString += (r.nextInt(9) + 1);

    //Generate the remaining digits between 0-9
    for(int x = 1; x < n; x++){
        randomNumString += r.nextInt(9);
    }

    //Parse and return
    return Long.parseLong(randomNumString);

}

Is there a better/more efficient solution than this?

*There are lots of solutions for generating random numbers in a specified range, I was more curious on the best way to generate random numbers given a set number of digits, as well as making the solution robust enough to handle any number of digits.

I did not want to have to pass in a min and max, but rather just the number of digits needed




Aucun commentaire:

Enregistrer un commentaire