Trying to find maximum length of ones in a binary representation including negative numbers. In the following code input_file
is a text file where:
- first line is a number of lines with sample integers
- every line staring from the second line has just one sample integer
An example file:
4 - number of samples
3 - sample
0 - ...
1 - ...
2 - ...
Result: 2
Task: print the maximum number of ones found among all sample integers in input file. Find solution that takes O(n) time and makes just one pass through all samples.
How to modify solution to work with negative integers of arbitrary (or at least for n ≤ 10000
) size?
Update:
As I understand binary representation of negative numbers is based on Two's complement (https://en.wikipedia.org/wiki/Two's_complement). So, for example:
+3 -> 011
-3 -> 101
How to convert integer to binary string representation taking its sign into account in general case?
def maxConsecutive(input):
return max(map(len,input.split('0')))
def max_len(input_file):
max_len = 0
with open(input_file) as file:
first_line = file.readline()
if not first_line:
return 0
k = int(first_line.strip()) # number of tests
for i in range(k):
line = file.readline().strip()
n = int(line)
xs = "{0:b}".format(n)
n = maxConsecutive(xs)
if n > max_len:
max_len = n
return max_len
print(max_len('input.txt'))
Update 2: This is a second task B from Yandex contest training page: https://contest.yandex.ru/contest/8458/enter/?lang=en
You need to register there to test your solution.
So far All solutions given here fail at test 9.
Update 3: Solution in Haskell that pass all Yandex tests
import Control.Monad (replicateM)
onesCount :: [Char] -> Int
onesCount xs = onesCount' xs 0 0
where
onesCount' "" max curr
| max > curr = max
| otherwise = curr
onesCount' (x:xs) max curr
| x == '1' = onesCount' xs max $ curr + 1
| curr > max = onesCount' xs curr 0
| otherwise = onesCount' xs max 0
getUserInputs :: IO [Char]
getUserInputs = do
n <- read <$> getLine :: IO Int
replicateM n $ head <$> getLine
main :: IO ()
main = do
xs <- getUserInputs
print $ onesCount xs