LeetCode · Daily Question · 2485. Find the central integer · prefix sum

Author: Xiao Xun
Link: https://leetcode.cn/problems/find-the-pivot-integer/solutions/2320800/qian-zhui-he-zhu-shi-chao-ji-xiang-xi-by-e4yp/
Source: LeetCode
copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

topic

 

example

 

train of thought

Title->Give you a positive integer n, find the central integer x that satisfies the following conditions:

  • The sum of all elements between 1 and x is equal to the sum of all elements between x and n.

First calculate the sum of the array, and then enumerate each position from the beginning to judge whether the current position meets the requirements of the question.

  • How to judge whether the current position meets the meaning of the question?
    • Whether the prefix sum on the left of the current position is equal to the prefix sum on the right

Code comments are super detailed

the code


int pivotInteger(int n){
    int sum = 0;
    for (int i = 0; i <= n; ++i) {
        sum += i;//记录前缀和
    }
    int temp = 0;
    for (int i = 1; i <= n; ++i) {
        temp += i;//记录左边前缀和
        if (temp == sum) return i;
        sum -= i;//记录右边前缀和
    }
    return -1;
}

作者:小迅
链接:https://leetcode.cn/problems/find-the-pivot-integer/solutions/2320800/qian-zhui-he-zhu-shi-chao-ji-xiang-xi-by-e4yp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Guess you like

Origin blog.csdn.net/m0_64560763/article/details/131393278