Here, We see Reaching Points LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
![Reaching Points LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Reaching Points LeetCode Solution
Table of Contents
Problem Statement
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)
.
Example 1:Input: sx = 1, sy = 1, tx = 3, ty = 5 Output: true Explanation: One series of moves that transforms the starting point to the target is: (1, 1) -> (1, 2) (1, 2) -> (3, 2) (3, 2) -> (3, 5)
Example 2:Input: sx = 1, sy = 1, tx = 2, ty = 2 Output: false
Example 3:Input: sx = 1, sy = 1, tx = 1, ty = 1 Output: true
Reaching Points Solution C++
class Solution {
public:
bool reachingPoints(int sx, int sy, int tx, int ty) {
while(sx < tx && sy < ty){
if(tx > ty) tx = tx%ty;
else ty = ty%tx;
}
if(sx == tx && sy<= ty && (ty-sy)%sx == 0) return true;
if(sy == ty && sx <= tx && (tx-sx)%sy == 0) return true;
return false;
}
};
Code language: PHP (php)
Reaching Points Solution Java
class Solution {
public boolean reachingPoints(int sx, int sy, int tx, int ty) {
while (tx >= sx && ty >= sy) {
if (tx == ty) break;
if (tx > ty) {
if (ty > sy) tx %= ty;
else return (tx - sx) % ty == 0;
} else {
if (tx > sx) ty %= tx;
else return (ty - sy) % tx == 0;
}
}
return (tx == sx && ty == sy);
}
}
Code language: PHP (php)
Reaching Points Solution JavaScript
var reachingPoints = function (sx, sy, tx, ty) {
if (sx > tx || sy > ty) return false;
if (sx === tx) return (ty - sy) % sx === 0;
if (sy === ty) return (tx - sx) % sy === 0;
if (tx > ty) return reachingPoints(sx, sy, tx % ty, ty);
else if (tx < ty) return reachingPoints(sx, sy, tx, ty % tx);
else return false;
}
Code language: JavaScript (javascript)
Reaching Points Solution Python
class Solution(object):
def reachingPoints(self, sx, sy, tx, ty):
if tx==0 or ty==0: return (sx, sy)==(tx, ty)
while not (sx==tx and sy==ty):
if sx>tx or sy>ty: return False
elif tx==ty: return ((0, ty)==(sx, sy) or (tx, 0)==(sx, sy))
if ty>tx:
if tx==sx: return (ty-sy)%sx==0
ty%=tx
else:
if ty==sy: return (tx-sx)%sy==0
tx%=ty
return True