Given a positive integer n
, find the pivot integer x
such that:
- The sum of all elements between
1
andx
inclusively equals the sum of all elements betweenx
andn
inclusively.
Return the pivot integer x
. If no such integer exists, return -1
. It is guaranteed that there will be at most one pivot index for the given input.
LeetCode Problem - 2485
class Solution {
// Method to find the pivot integer in the range [1, n]
public int pivotInteger(int n) {
int sum1 = 0;
// Calculate the sum of integers from 1 to n
for (int i = 1; i <= n; i++){
sum1 += i;
// Calculate the sum of integers from i to n using xTon method
int sum2 = xTon(i, n);
// Check if the sums are equal, indicating the pivot integer
if (sum1 == sum2){
return i;
}
}
// If no pivot integer is found, return -1
return -1;
}
// Declare a variable to store the sum calculated in xTon method
int temp2 = 0;
// Method to calculate the sum of integers from b to n
public int xTon(int b, int n){
// Initialize the sum variable
temp2 = 0;
// Calculate the sum of integers from b to n
for (int i = b; i <= n; i++){
temp2 += i;
}
// Return the sum
return temp2;
}
}