谷歌Foobar挑战:奇特的平衡

时间:2015-09-11 06:45:10

标签: algorithm math ternary ternary-representation

我解决了将01000000000之间的基数为10的正整数转换为平衡三元形式的问题,这是Google代码挑战的一部分。它似乎适用于我在约束条件下测试过的各种情况,但由于某种原因它未通过测试4和5。你能发现这个有什么问题吗?

def answer(binary):

    # Convert to ternary
    ternary = convertToTernary(binary)

    # Conver to balanced ternary
    balancedTernary = balance(ternary)

    return balancedTernary

def balance(tForm):
    tForm.append(0)
    bTernary = tForm

    i = 0;
    N = len(tForm)
    for i in range(N - 1):
        if tForm[i] == 2:
            tForm[i] = 'L'  # Convert to custom convention now
            tForm[i+1] += 1
        elif tForm[i] > 2:
            tForm[i] = 0
            tForm[i+1] += 1

    # Apply custom convention to the rest of the coefficients
    for i in range(len(tForm)):
        if tForm[i] == 0:
            tForm[i] = '-'
        elif tForm[i] == 1:
            tForm[i] = 'R'
        else:
            tForm[i] = 'L'

    return bTernary

def convertToTernary(binary):
    tForm = []

    while binary > 0:
        tForm.append(binary % 3)
        binary /= 3

    return tForm

0 个答案:

没有答案