[Python] How can I get the length of repeating decimal?

Discussão em 'Python' iniciado por Stack, Outubro 1, 2024.

  1. Stack

    Stack Membro Participativo

    I got an interview and the question is how to get the length of repeating decimal?

    For example

    1/3=0.3333..., it returns 1,
    5/7=0.7142857142857143, it returns 6, since 714285 is the repeating decimal.
    1/15=0.066666666666666, it returns 1.
    17/150=0.11333333333333333, it returns 1. since 3 is the repeating decimal.


    And I have tried to write a code

    def solution(a, b):
    n = a % b
    if n == 0:
    return 0

    mem = []
    n *= 10

    while True:
    n = n % b
    if n == 0:
    return 0
    if n in mem:
    i = mem.index(n)
    return len(mem[i:])
    else:
    mem.append(n)
    n *= 10


    However, my code can't pass all tests. And it's time complexity is O(n*logn). How can I improve that and make its time complexity O(n)?

    Continue reading...

Compartilhe esta Página