[LeetCode] Reaching Points

780. Reaching Points

Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.

The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
bool reachingPoints(int sx, int sy, int tx, int ty) {
while(tx >= sx and ty >= sy) {
if(tx == sx and ty == sy) return true;
if(ty == tx) return false;
if(tx < ty) {
int n = (ty - tx) / tx + 1;
if(ty - n * tx >= sy) ty = ty - n * tx;
else {
n = (ty - sy) / tx;
if(n == 0) return false;
ty = ty - n * tx;
}
} else {
int n = (tx - ty) / ty + 1;
if(tx - n * ty >= sx) tx = tx - n * ty;
else {
n = (tx - sx) / ty;
if(n == 0) return false;
tx = tx - n * ty;
}
}
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/26/PS/LeetCode/reaching-points/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.