2485. Find the Pivot Integer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int pivotInteger(int n) {
// 根据等差数列求和公式,我们可求出 1 至 x 与 x 至 n 的和
// 1 至 x 的和:x * (x + 1) / 2
// x 至 n 的和:(n - x + 1) * (x + n) / 2
// 两式相等,化简可得:x ^ 2 = (n ^ 2 + n) / 2
// 若 x 可为整数,则说明找到了值,若 x 不为整数,则无法找到值

int x2 = (n * n + n) / 2;
int x = (int) Math.sqrt(x2);
if (x * x == x2) {
return x;
} else {
return -1;
}
}
}

References

2485. Find the Pivot Integer