Skip to content

Instantly share code, notes, and snippets.

@mrjohannchang
Last active May 29, 2017 02:01
Show Gist options
  • Save mrjohannchang/051c78d38a127d0579928b884625aa1e to your computer and use it in GitHub Desktop.
Save mrjohannchang/051c78d38a127d0579928b884625aa1e to your computer and use it in GitHub Desktop.
def solve(s: str, n: int, iseven: bool):
if n <= 0:
print(s)
return
i: int
for i in range(10) if iseven else range(9, -1, -1):
solve(s + chr(ord('0') + i), n - 1, i % 2 == 0 if iseven else i % 2 == 1)
solve('', int(input()), True)
@Wendly
Copy link

Wendly commented May 28, 2017

迴圈的解法

n = int(input())

numMax = 10 ** n
num = 0

while num < numMax:
    print("%0*d" % (n, num))

    direct = 0
    oldNum = num
    for i in range(0, n):
        direct += oldNum % 10
        oldNum //= 10

    dNum = 1
    oldNum = num
    while True:
        digit = oldNum % 10
        oldNum //= 10
        direct -= digit

        if (direct % 2) == 0 and digit < 9:
                num += dNum
                break
        if (direct % 2) == 1 and digit > 0:
                num -= dNum
                break

        dNum *= 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment