[LeetCode] Find the Pivot Integer

2485. Find the Pivot Integer

Given a positive integer n, find the pivot integer x such that:

  • The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n 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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int pivotInteger(int n) {
int total = n * (n + 1) / 2, sum = 0;
for(int i = 1; i <= n; i++) {
sum += i;
if(sum == total) return i;
total -= i;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/27/PS/LeetCode/find-the-pivot-integer/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.