Hello experts,
I am converting a number into its binary output as :
read n
echo "obase=2;$n" | bc
I wish to count the maximum continuous occurrences of the digit 1.
Example :
1. The binary equivalent of 5 = 101. Hence the output must be 1.
2. The binary equivalent of 6 = 110. Hence the output must be 2.
3. The binary equivalent of 9 = 1001. Hence the output must be 1.
4. The binary equivalent of 13 = 1101. Hence the output must be 2
Could you please help.
Thanks,
Haider
how about this ?
$ echo "111110000111000" | tr '0' '\n' | sort -nr | awk 'NR==1{print length}'
5
$ echo "111001100111000" | tr '0' '\n' | sort -nr | awk 'NR==1{print length}'
3
$ echo "1110011001111000" | tr '0' '\n' | sort -nr | awk 'NR==1{print length}'
4
Hello H squared,
Could you please try following.
cat script.ksh
echo "Enter a number here.."
read num
echo "obase=2;$num" | bc | awk '{print $0;while(match($0,/1+/)){;q=q>substr($0,RSTART,RLENGTH)?q:substr($0,RSTART,RLENGTH);$0=substr($0,RLENGTH+1)}} END{print length(q)}'
So let's say we will run it as follows.
./script.ksh
Enter a number here..
12312446577991213
101011101111100001101011011100100110001101111000101101
5
./script.ksh
Enter a number here..
12111113312
1011010001111000001110110001100000
4
EDIT: Adding a non-one liner form of solution on same now.
echo "Enter a number here.."
read num
echo "obase=2;$num" | bc | awk '{print $0;
while(match($0,/1+/)){
q=q>substr($0,RSTART,RLENGTH)?q:substr($0,RSTART,RLENGTH);
$0=substr($0,RLENGTH+1)
}
}
END {
print length(q)
}
'
Thanks,
R. Singh
1 Like
In a bash script, you could split the record on zeros then count the length of each 'field' it creates, perhaps like this:-
#!/bin/bash
read -p "Enter a number here.. " num
one_strings="$(echo \"obase=2\;$num\" | bc | tr '0' ' ' )"
max_found_length=0
for a_string in $one_strings # Unquoted to ensure it splits up for the read
do
a_string_length="${#a_string}"
if [ $a_string_length -gt $max_found_length ]
then
max_found_length=$a_string_length
fi
done
echo "Max length of consecutive 1's found was $max_found_length"
Apart from the conversion to binary, this is all internal to the shell, so should be quick.
For ksh you will need to change the read:-
read num?"Enter a number here.. "
I hope that this helps,
Robin