论坛首页 编程语言技术论坛

Ruby中判断奇偶数最简单最效率的办法

浏览 5440 次
精华帖 (0) :: 良好帖 (7) :: 新手帖 (0) :: 隐藏帖 (12)
作者 正文
   发表时间:2008-03-17  
不用多说,办法如下:
def even?(value)
  value[0]!=1
end

even?(10) #true
even?(11) #false

这下好了,连&都不用写了。
可能有点吹毛求疵~权当娱乐
   发表时间:2008-03-17  
active_support提供这样的实现了。
0 请登录后投票
   发表时间:2008-03-17  
def even2?(value)
  value & 1 == 0
end

这个仿佛要快一点点。我用benchmark跑了一下,跑15秒左右的数据大概少用0.5秒。不过不知道准不准,也不知道这点差异是否有效。
0 请登录后投票
   发表时间:2008-03-17  
active_support的even_odd.rb扩展了数值类型,源码全文是:
module ActiveSupport #:nodoc:
  module CoreExtensions #:nodoc:
    module Integer #:nodoc:
      # For checking if a fixnum is even or odd. 
      # * 1.even? # => false
      # * 1.odd?  # => true
      # * 2.even? # => true
      # * 2.odd? # => false
      module EvenOdd
        def multiple_of?(number)
          self % number == 0
        end

        def even?
          multiple_of? 2
        end if RUBY_VERSION < '1.9'

        def odd?
          !even?
        end if RUBY_VERSION < '1.9'
      end
    end
  end
end


ruby1.9加了Integer#odd?, #even?,所以它在里面做了判断。
Fixnum#[]原来是位操作:
引用
Bit Reference---Returns the nth bit in the binary representation of fix, where fix[0] is the least significant bit.

0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics