인수가 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
.