【问题标题】:Is there any other way to replace consecutive repeating digits with 0 in an integer without converting it to string? [duplicate]有没有其他方法可以用整数中的 0 替换连续的重复数字而不将其转换为字符串? [复制]
【发布时间】:2019-12-12 03:54:43
【问题描述】:

给定一个整数,可以是 10 的 18 次方,我们必须用零替换所有连续的重复数字。

我尝试过将整数转换为字符串,但是从整数到字符串的类型转换需要很多时间。有什么方法可以在不将其转换为字符串的情况下执行该功能。我的代码通过将整数转换为字符串 -:

def replace(l):
    l1 = str(l)
    s = l1[0]
    temp = s[0]

    for i in range(1, len(l1)):
        if l1[i] == temp:
            s += '0'
        else:
            s += l1[i]
            temp = l1[i]

    l = int(s)
    return l 

示例-:设整数为 1222433444
预期输出 -: 1200430400

【问题讨论】:

  • 如果你不需要超过 10^18,你可以使用 int64。
  • 我刚刚检查过了。如果这是真的“大到 10 的 18 次方”,那么您绝对应该使用 int64。好吧,它是用 C++ 标记的。在 Python 中,这无关紧要。它可以处理大量数字没问题。

标签: python python-3.x type-conversion


【解决方案1】:

连接stringstringstringstring 需要时间。每次您将某些东西连接到 string 时,旧的都会被丢弃并创建一个新的 - 这需要计算时间。 python 中的Strings不可变的

改用list 并只创建一次最终的string

def replace(l):
    l1 = list(str(l))     # use a list
    v = l1[0]                               # first char is our start v
    for idx,value in enumerate(l1[1:],1):   # we do all the others starting at index 1
        if l1[idx] == v:
            l1[idx] = '0'                   # replace list element
        else:
            v = l1[idx]                     # or replace v if different

    l = int(''.join(l1))               # only create one string & convert to int 
    return l 


print(replace(1222433444))  # input
print(1200430400)           # your expected

输出:

1200430400
1200430400

【讨论】:

    【解决方案2】:

    虽然使用字符串 正确 可能是最好的解决方案,但您可以直接迭代数字,而根本不需要执行到字符串的转换。有几种方法可以做到这一点。最简单的可能是从最大的数字开始:

    from math import floor, log10
    
    def replace(n):
        digit_count = floor(log10(n))
        prev = 0
        result = 0
        power = 10**digit_count
        for i in range(digit_count, -1, -1):
            digit = (n // power) % 10
            result *= 10
            if digit != prev:
                result += digit
                prev = digit
            power //= 10
    

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 2019-12-24
      • 2021-11-02
      • 2019-11-22
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      相关资源
      最近更新 更多