在Julia找到小于n的两个下一个幂

Ale*_*ley 3 julia

我需要在Julia中找到小于给定数字的下两个幂.

smallerpoweroftwo(15)应该返回,8smallerpoweroftwo(17)应该返回16

到目前为止,我有这个,但搜索一串比特对我来说似乎有点笨拙.也许它不...任何想法?

function smallerpoweroftwo(n::Int)
    2^(length(bits(n)) - search(bits(n), '1'))
end
Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑:我主要想的是使用按位算法有更优雅的方法来做到这一点.或者在某些其他语言中是否存在位长函数?

Ste*_*ski 6

Julia的标准库具有prevpow2nextpow2功能:

help?> prevpow2
search: prevpow2 prevpow prevprod

  prevpow2(n)

  The largest power of two not greater than n. Returns 0 for n==0, and returns -prevpow2(-n) for negative
  arguments.

help?> nextpow2
search: nextpow2 nextpow nextprod

  nextpow2(n)

  The smallest power of two not less than n. Returns 0 for n==0, and returns -nextpow2(-n) for negative
  arguments.
Run Code Online (Sandbox Code Playgroud)

prevpow2功能应该做你想要的.