题解 | #杨辉三角的变形#
杨辉三角的变形
http://www.nowcoder.com/practice/8ef655edf42d4e08b44be4d777edbf43
题目的关键点在于找规律,如下代码可以打印出从第三行开始的奇数和偶数的规律(0表示偶数,1表示奇数)
def func(n):
odd = [1, 1, 1]
for i in range(3, n+1):
odd = [1, odd[0]^odd[1]] + [odd[j]^odd[j+1]^odd[j+2] for j in range(len(odd) - 2)] + [odd[-2]^odd[-1], 1]
print(odd)
return odd.index(0) if 0 in odd else -1
"""
func(100)
[1, 0, 1, 0, 1]
[1, 1, 0, 1, 0, 1, 1]
[1, 0, 0, 0, 1, 0, 0, 0, 1]
[1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1]
[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1]
[1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]
[1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1]
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1]
[1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1]
[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]
[1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1]
[1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1]
[1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]
[1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1]
[1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]
"""
经过观察发现每4行偶数出现的位置就会循环一次(位置分别是[2, 3, 2, 4])
while True:
try:
n = int(input())
if n == 1 or n == 2:
print(-1)
continue
n -= 3
n %= 4
res = [2,3,2,4]
print(res[n])
except EOFError: break