-1

We are given an integer which can be large as 10 to the power of 18 and we have to replace all consecutive repeating digits with zero.

I have tried by converting the integer to string but it takes a lot of time in doing type conversion from integer to string. Is there any way to do the function without converting it to string. My code by converting the integer to string -:

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 

Example-: Let integer be 1222433444
Expected output -: 1200430400

khelwood
  • 55,782
  • 14
  • 81
  • 108
ayusht
  • 21
  • 3
  • If you don't need more than 10^18, you could use int64 for that. – Machta Aug 04 '19 at 07:48
  • 1
    [Format your code properl](https://stackoverflow.com/editing-help)y please! – πάντα ῥεῖ Aug 04 '19 at 07:49
  • 1
    I just checked. If this is true "be large as 10 to the power of 18", you should definitely use int64. Well it was flagged with C++. In Python it doesn't matter. It can deal with huge numbers no problem. – Machta Aug 04 '19 at 07:56

2 Answers2

1

What takes time is concattenating string to string to string to string. Every time you concat something to a string the old one is discarded and a new one is created - this takes computation time. Strings in python are immuteable.

Use a list instead and create the final string only once:

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

Output:

1200430400
1200430400
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

While using a string properly is probably the best solution, you can iterate over the digits directly, without performing a conversion to string at all. There are a couple of ways of doing this. The simplest is probably to start with the largest digit:

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
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264