到达终点
给定四个整数 sx , sy ,tx 和 ty,如果通过一系列的转换可以从起点 (sx, sy) 到达终点 (tx, ty),则返回 true,否则返回 false。 从点 (x, y) 可以转换到 (x, x+y) 或者 (x+y, y)。 来源:力扣(LeetCode)
AC代码class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
dx, dy = tx, ty
if dx == sx and dy == sy:
return True
while dx > 0 and dy > 0:
if dx > dy:
dx = dx - max((dx - sx) // dy, 1) * dy
else:
dy = dy - max((dy - sy) // dx, 1) * dx
if dx == sx and dy == sy:
return True
else:
return False
官方代码
class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
while sx sy:
if tx > ty:
tx %= ty
else:
ty %= tx
if tx == sx and ty == sy:
return True
elif tx == sx:
return ty > sy and (ty - sy) % tx == 0
elif ty == sy:
return tx > sx and (tx - sx) % ty == 0
else:
return False
# 作者:LeetCode-Solution
1、直接取模也是个不错的选择,但是这样的话需要考虑当tx不能再减小或者其他的情况,感觉不如直接tx < 0来的方便