Generate random number of certain amount of digits

后端 未结 7 1909
不知归路
不知归路 2021-01-18 10:51

Hy,

I have a very Basic Question which is :

How can i create a random number with 20 digits no floats no negatives (basically an Int) in Swift ?

Than

7条回答
  •  终归单人心
    2021-01-18 11:34

    Here is some pseudocode that should do what you want.

    generateRandomNumber(20)
    func generateRandomNumber(int numDigits){
       var place = 1
       var finalNumber = 0;
       for(int i = 0; i < numDigits; i++){
          place *= 10
          var randomNumber = arc4random_uniform(10)
          finalNumber += randomNumber * place
      }
      return finalNumber
    }
    

    Its pretty simple. You generate 20 random numbers, and multiply them by the respective tens, hundredths, thousands... place that they should be on. This way you will guarantee a number of the correct size, but will randomly generate the number that will be used in each place.

    Update

    As said in the comments you will most likely get an overflow exception with a number this long, so you'll have to be creative in how you'd like to store the number (String, ect...) but I merely wanted to show you a simple way to generate a number with a guaranteed digit length. Also, given the current code there is a small chance your leading number could be 0 so you should protect against that as well.

提交回复
热议问题