![检查 2 的 pow 有限制](https://linux22.com/image/142447/%E6%A3%80%E6%9F%A5%202%20%E7%9A%84%20pow%20%E6%9C%89%E9%99%90%E5%88%B6%20.png)
我需要编写一个条件,这样如果参数为 1 (即 2 ^ 0 = 1 ),它将跳过它。例如:
powsnsums 1 2 8
2
powsnsums 1 16
1
#!/bin/bash
# loop over all numbers on the command line
# note: we don't verify that these are in fact numbers
for number do
w=0 # Hamming weight (count of bits that are 1)
n=$number # work on $n to save $number for later
# test the last bit of the number, and right-shift once
# repeat until number is zero
while (( n > 0 )); do
if (( (n & 1) == 1 )); then
# last bit was 1, count it
w=$(( w + 1 ))
fi
if (( w > 1 )); then
# early bail-out: not a power of 2
break
fi
# right-shift number
n=$(( n >> 1 ))
done
if (( w == 1 )); then
# this was a power of 2
printf '%d\n' "$number"
fi
done
答案1
if [ "$number" -eq 1 ]; then
continue
fi
或者
if (( number == 1 )); then
continue
fi
$number
如果数值等于 1,这将使循环跳到下一次迭代。测试将for number do
在线下进行。