Bash Binary Gap
binary_gap() {
local _n=$1
local _bin=""
if (( _n == 0 )); then
_bin="0"
else
local _x=$_n
while (( _x > 0 )); do
_bin="$(( _x % 2 ))$_bin"
_x=$(( _x / 2 ))
done
fi
_bin="${_bin#"${_bin%%[!0]*}"}"
_bin="${_bin%"${_bin##*[!0]}"}"
local _gap=0 _len=0
local -a _zeros
IFS='1' read -ra _zeros <<< "$_bin"
local _z
for _z in "${_zeros[@]}"; do
_len=${#_z}
(( _len > _gap )) && _gap=$_len
done
echo "$_gap"
}
This turns the number into binary, ignores zeroes outside the edges, and finds the longest run of zeroes between 1s.