#2485

Find the Pivot Integer

newbie · 135 · lc easy +13 · verified · 83.8% accepted · 1,434 likes · top 95%

Description

Given a positive integer n, find a pivot integer x such that the sum of all integers from 1 to x (inclusive) equals the sum of all integers from x to n (inclusive). Return x, or -1 if no such integer exists. At most one pivot will exist for any valid input.

Example 1:

Input: n = 8
Output: 6
Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.

Example 2:

Input: n = 1
Output: 1
Explanation: 1 is the pivot integer since: 1 = 1.

Example 3:

Input: n = 4
Output: -1
Explanation: It can be proved that no such integer exist.

Code

1
2
3