我正在解决一个问题,您将一个以 10 为底的正整数在0
和之间1000000000
转换为平衡的三元形式,作为 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