There exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps.
In one step , you can move from point (x, y) to any one of the following points:
(x, y - x)
(x - y, y)
(2 * x, y)
(x, 2 * y)
Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return trueif you can reach the point from(1, 1)using some number of steps, andfalseotherwise.
The allowed moves either double a coordinate or subtract one coordinate from the other. This suggests that the greatest common divisor (GCD) and the parity (odd/even) of the coordinates are preserved or change in a predictable way. The key is to analyze the GCD and its properties under these operations.
Doubling a coordinate does not change the GCD, and subtracting one coordinate from the other also preserves the GCD. Thus, the GCD of (targetX, targetY) must be a power of two for the point to be reachable from (1, 1), since the GCD of (1, 1) is 1 and only powers of two can be reached by repeated doublings. If the GCD is not a power of two, the point is not reachable.
classSolution {
public:bool isReachable(int targetX, int targetY) {
int g = gcd(targetX, targetY);
return (g & (g -1)) ==0;
}
intgcd(int a, int b) {
return b ==0? a : gcd(b, a % b);
}
};
classSolution {
publicbooleanisReachable(int targetX, int targetY) {
int g = gcd(targetX, targetY);
return (g & (g - 1)) == 0;
}
privateintgcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
1
2
3
4
5
6
7
classSolution {
funisReachable(targetX: Int, targetY: Int): Boolean {
fungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % a)
val g = gcd(targetX, targetY)
return g and (g - 1) ==0 }
}
1
2
3
4
5
6
7
8
classSolution:
defis_reachable(self, targetX: int, targetY: int) -> bool:
defgcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
g = gcd(targetX, targetY)
return g & (g -1) ==0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnis_reachable(target_x: i32, target_y: i32) -> bool {
fngcd(mut a: i32, mut b: i32) -> i32 {
while b !=0 {
let t = b;
b = a % b;
a = t;
}
a
}
let g = gcd(target_x, target_y);
g & (g -1) ==0 }
}