-
Notifications
You must be signed in to change notification settings - Fork 1
/
200909-binary-gap.sh
92 lines (92 loc) · 2.32 KB
/
200909-binary-gap.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/bin/bash
## binary-gap
## - returns length of binary gap in a integer
## version 0.0.1 - initial
##################################################
## problem:
## - find the length of longest contiguous string
## of 0s between 1 or more 1s in the binary
## representation of a positive integer
##################################################
## algorithm:
## 1. convert positive integer into binary string
## 1. trim leading and ending zeros from string
## 1. split string into list of gaps using
## delimiter '1'
## 1. return length of longest gap
##################################################
hex2binary() { { local hex ; hex="${1}" ; }
for i in $( seq ${#hex} )
do
case ${hex:$(( ${i} - 1 )):1} in
0) bin='0000' ;;
1) bin='0001' ;;
2) bin='0010' ;;
3) bin='0011' ;;
4) bin='0100' ;;
5) bin='0101' ;;
6) bin='0110' ;;
7) bin='0111' ;;
8) bin='1000' ;;
9) bin='1001' ;;
a) bin='1010' ;;
b) bin='1011' ;;
c) bin='1100' ;;
d) bin='1101' ;;
e) bin='1110' ;;
f) bin='1111' ;;
esac
echo -n "${bin}"
done
}
dec2hex() { { local -i dec ; dec="${1}" ; }
printf '%x\n' ${n}
}
trim() { { local bin ; bin="${1}" ; }
echo "${bin}" | sed -e 's/^0*//' -e 's/0*$//' -e 's/^1*//' -e 's/1*$//'
}
if-debug() {
test ! ${DEBUG:-false} = "true"
}
binary-gap() { { local -i n ; n="${1}" ; }
if-debug || {
echo -e "dec: \t\t${n}"
echo -e "hex: \t\t$( dec2hex ${n} )"
echo -e "bin: \t\t$( hex2binary $( dec2hex ${n} ) )"
echo -e "bin(trimmed): \t$( trim $( hex2binary $( dec2hex ${n} ) ) )"
} 1>&2
local bin
local bin_trim
local gap
bin=$( hex2binary $( dec2hex ${n} ) )
bin_trim=$( trim ${bin} )
gap=$(
IFS='1'
for b in ${bin_trim}
do
test ! "${b}" = '' || continue
echo ${b}
done | sort | tail -1
)
if-debug || {
test ! "${gap}" || {
echo -ne "bin(match):\t"
echo "${bin}" | grep -e "${gap}" --color=auto
}
} 1>&2
echo "${#gap}"
}
##################################################
if [ ${#} -eq 1 ]
then
true
else
exit 1 # wrong args
fi
##################################################
binary-gap ${@}
##################################################
## generated by create-stub2.sh v0.1.2
## on 9 Sep 2020
## see <https://github.com/temptemp3/sh2>
##################################################