选择大于Integer.MAX_VALUE的范围内的随机整数? [英] Choose random integer in a range bigger than Integer.MAX_VALUE?

查看:121
本文介绍了选择大于Integer.MAX_VALUE的范围内的随机整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道还有一个关于范围内随机性的问题,但是他们的答案都无法完成我想做的事情.实际上,它们具有与我相同的错误.我写了这个简单的函数来生成带范围的随机数.

I know there are another questions about random in a range but none of their answers accomplishes what I am trying to do. Actually they have the same error I have. I wrote this simple function to generate random with range.

Random m_random = new Random();
...
public int RandomWithRange(int min, int max) {
    return m_random.nextInt(max - min + 1) + min;
}

如果范围大于Integer.MAX_VALUE,则抛出IllegalArgumentException:n必须为正.我知道它溢出并变成负数.我的问题是如何处理?

If range is bigger than Integer.MAX_VALUE, it throws an IllegalArgumentException: n must be positive. I know it overflows and turn to a negative number. My question is how to handle that?

示例范围;

  • [0,Integer.MAX_VALUE]
  • [Integer.MIN_VALUE,Integer.MAX_VALUE]
  • [-100,Integer.MAX_VALUE]

注意:最小值和最大值必须包含在内.

Note: min and max must be inclusive.

推荐答案

您遇到的问题是(max - min)溢出并为您提供负值.

The problem you have is that (max - min) overflows and gives you a negative value.

您可以改用long.

public int randomWithRange(int min, int max) {
    return (int) ((m_random.nextLong() & Long.MAX_VALUE) % (1L + max - min)) + min;
}

这篇关于选择大于Integer.MAX_VALUE的范围内的随机整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆