The sum from 1 to x is x * (x + 1) / 2. The sum from x to n is n * (n + 1) / 2 - (x - 1) * x / 2. Set these equal and solve for x. This leads to a quadratic equation, and the solution must be an integer.
classSolution {
publicintpivotInteger(int n) {
int total = n * (n + 1) / 2;
int x = (int)Math.sqrt(total);
return x * x == total ? x : -1;
}
}
1
2
3
4
5
6
7
classSolution {
funpivotInteger(n: Int): Int {
val total = n * (n + 1) / 2val x = kotlin.math.sqrt(total.toDouble()).toInt()
returnif (x * x == total) x else -1 }
}
1
2
3
4
5
classSolution:
defpivotInteger(self, n: int) -> int:
total = n * (n +1) //2 x = int(total **0.5)
return x if x * x == total else-1
1
2
3
4
5
6
7
impl Solution {
pubfnpivot_integer(n: i32) -> i32 {
let total = n * (n +1) /2;
let x = (total asf64).sqrt() asi32;
if x * x == total { x } else { -1 }
}
}