DEV Community

özkan pakdil
özkan pakdil

Posted on

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.

Solution

class Solution {
    public int pivotInteger(int n) {
        if(n==1) return 1;
        for (int i = n - 1; i > 0; i--) {
            if (((n * (n + 1)) / 2) - ((i * (i - 1)) / 2) == (i * (i + 1)) / 2)
                return i;
        }

        return -1;
    }
}
Enter fullscreen mode Exit fullscreen mode

reference:
https://leetcode.com/problems/find-the-pivot-integer/
https://math.stackexchange.com/a/2713667/1053103

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up