随机产生一个限定范围的long型数字

最近抓取新浪微博的数据,需要产生一些随机微博的ID。由于新浪微博的ID是一个16位的数字,所以在Java程序中要用long型来产生。并且,微博ID是有一定范围的,如果不限定范围,命中的概率会很低。这里就需要限定产生随机数的范围。然而,在Java SDK中,只提供了一个产生整数的、可限定范围的方法:

  1. public int nextInt(int n) {  
  2.      if (n<=0)  
  3.                 throw new IllegalArgumentException("n must be positive");  
  4.   
  5.      if ((n & -n) == n)  // i.e., n is a power of 2  
  6.          return (int)((n * (long)next(31)) >> 31);  
  7.   
  8.      int bits, val;  
  9.      do {  
  10.          bits = next(31);  
  11.          val = bits % n;  
  12.      } while(bits - val + (n-1) < 0);  
  13.      return val;  
  14.  }  

看了一下官方文档,并到网上查阅了一些资料。认为如下实现是最好的获得限制范围的long型数字的方法:
  1. public long nextLong(Random rng, long n) {  
  2.    // error checking and 2^x checking removed for simplicity.  
  3.    long bits, val;  
  4.    do {  
  5.       bits = (rng.nextLong() << 1) >>> 1;  
  6.       val = bits % n;  
  7.    } while (bits-val+(n-1) < 0L);  
  8.    return val;  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值