正则表达式(ECMAScript),85 73 71字节
^((?=(x*?)\2(\2{4})+$|(x*?)(\4\4xx)*$)(\2\4|(x*)\5\7\7(?=\4\7$\2)\B))*$
在线尝试!
Deadcode的解释
下面说明了早期的73字节版本。
^((?=(x*?)\2(\2{4})+$)\2|(?=(x*?)(\4\4xx)*$)(\4|\5(x*)\7\7(?=\4\7$)\B))+$
由于ECMAScript正则表达式的局限性,一种有效的策略通常是一次转换一个数字,同时又要保持每个步骤所需的属性不变。例如,要测试一个完美的平方或2的幂,请减少大小,同时在每一步将其保持为平方或2的幂。
以下是此解决方案在每个步骤中所做的工作:
1
1
1
10
01
01
ones>zeroes1
ones>zeroes⇔ones−1>zeroes−1
当这些重复的步骤不再进行时,最终结果将是连续的1
位串(很重,表示原始数也很重),或者是2的幂,表示原始数并不繁重。
当然,尽管以上是根据数字的二进制表示形式的印刷操作描述了这些步骤,但实际上它们是作为一元算术实现的。
# For these comments, N = the number to the right of the "cursor", a.k.a. "tail",
# and "rightmost" refers to the big-endian binary representation of N.
^
( # if N is even and not a power of 2:
(?=(x*?)\2(\2{4})+$) # \2 = smallest divisor of N/2 such that the quotient is
# odd and greater than 1; as such, it is guaranteed to be
# the largest power of 2 that divides N/2, iff N is not
# itself a power of 2 (using "+" instead of "*" is what
# prevents a match if N is a power of 2).
\2 # N = N - \2. This changes the rightmost "10" to a "01".
| # else (N is odd or a power of 2)
(?=(x*?)(\4\4xx)*$) # \4+1 = smallest divisor of N+1 such that the quotient is
# odd; as such, \4+1 is guaranteed to be the largest power
# of 2 that divides N+1. So, iff N is even, \4 will be 0.
# Another way of saying this: \4 = the string of
# contiguous 1 bits from the rightmost part of N.
# \5 = (\4+1) * 2 iff N+1 is not a power of 2, else
# \5 = unset (NPCG) (iff N+1 is a power of 2), but since
# N==\4 iff this is the case, the loop will exit
# immediately anyway, so an unset \5 will never be used.
(
\4 # N = N - \4. If N==\4 before this, it was all 1 bits and
# therefore heavy, so the loop will exit and match. This
# would work as "\4$", and leaving out the "$" is a golf
# optimization. It still works without the "$" because if
# N is no longer heavy after having \4 subtracted from it,
# this will eventually result in a non-match which will
# then backtrack to a point where N was still heavy, at
# which point the following alternative will be tried.
|
# N = (N + \4 - 2) / 4. This removes the rightmost "01". As such, it removes
# an equal number of 0 bits and 1 bits (one of each) and the heaviness of N
# is invariant before and after. This fails to match if N is a power of 2,
# and in fact causes the loop to reach a dead end in that case.
\5 # N = N - (\4+1)*2
(x*)\7\7(?=\4\7$) # N = (N - \4) / 4 + \4
\B # Assert N > 0 (this would be the same as asserting N > 2
# before the above N = (N + \4 - 2) / 4 operation).
)
)+
$ # This can only be a match if the loop was exited due to N==\4.