【发布时间】:2020-07-19 12:25:14
【问题描述】:
试图在包括负数的二进制表示中找到最大长度。在以下代码中input_file 是一个文本文件,其中:
- 第一行是包含样本整数的行数
- 从第二行开始的每一行只有一个样本整数
一个示例文件:
4 - 样本数
3 - 样本
0 - ...
1 - ...
2 - ...
结果:2
任务:打印输入文件中所有样本整数中找到的最大数。找到需要 O(n) 时间并且只通过所有样本一次的解决方案。
如何修改解决方案以使用任意大小的负整数(或至少对于n ≤ 10000)?
更新:
据我了解,负数的二进制表示基于二进制补码 (https://en.wikipedia.org/wiki/Two's_complement)。所以,例如:
+3 -> 011
-3 -> 101
在一般情况下如何将整数转换为二进制字符串表示并考虑其符号?
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'))
更新 2: 这是来自 Yandex 竞赛培训页面的第二个任务 B: https://contest.yandex.ru/contest/8458/enter/?lang=en
您需要在那里注册以测试您的解决方案。
到目前为止,这里给出的所有解决方案都在测试 9 中失败。
更新 3:通过所有 Yandex 测试的 Haskell 解决方案
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
【问题讨论】:
-
我对 Haskell 不太熟悉,但似乎该函数希望每一行都已经表示为 1 和 0 的字符串。 oneCount 的签名接受一个字符数组(即一个字符串)并返回一个数字,该数字是字符串中最大连续的“1”字符。在该代码中,我看不到整数值在哪里转换为它的位表示。它似乎没有比
max(map(len,bits.split("0"))) -
谢谢,会查的!