Generating 10 digits unique random number in java

前端 未结 9 599
执念已碎
执念已碎 2020-12-09 10:52

I am trying with below code to generate 10 digits unique random number. As per my req i have to create around 5000 unique numbers(ids). This is not working as expected. It a

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 11:20

    A general solution to return a 'n' digit number is

    Math.floor(Math.random() * (9*Math.pow(10,n-1))) + Math.pow(10,(n-1))
    

    For n=3, This would return numbers from 100 to 999 and so on.

    You can even control the end range, i.e from 100 to 5xx but setting the "9" in the above equation "5" or any other number from 1-9

提交回复
热议问题