您的实现将整数转换为以2为底的字符串,然后访问字符串中的每个字符。相反,您可以使用
<<和来访问整数中的每个位
&。这样做将避免访问每个位两次(首先将其转换为字符串,然后检查结果字符串中是否为“
1”)。它还将避免为该字符串分配内存,然后为您检查的每个子字符串分配内存。
您可以通过访问1 << 0,1 << 1,…,1 <<(x.bit_length)来检查整数的每个位。
例如:
def max_gap(x): max_gap_length = 0 current_gap_length = 0 for i in range(x.bit_length()): if x & (1 << i): # Set, any gap is over. if current_gap_length > max_gap_length: max_gap_length = current_gap_length current_gap_length = 0 else: # Not set, the gap widens. current_gap_length += 1 # Gap might end at the end. if current_gap_length > max_gap_length: max_gap_length = current_gap_length return max_gap_length



