diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /find_pivot_integer.c | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'find_pivot_integer.c')
-rw-r--r-- | find_pivot_integer.c | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/find_pivot_integer.c b/find_pivot_integer.c new file mode 100644 index 0000000..53175ec --- /dev/null +++ b/find_pivot_integer.c @@ -0,0 +1,28 @@ +// 2485. Find the Pivot Integer +#include "leetcode.h" + +/* + * 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. + */ + +int pivotInteger(int n) { + int l = 1, r = n, sum = n * (n + 1) / 2; + while (l < r) { + int m = (l + r) / 2; + if (m * m - sum < 0) + l = m + 1; + else + r = m; + } + return !(l * l - sum) ? l : -1; +} + +int main() { + printf("%d\n", pivotInteger(8)); // expect: 6 + printf("%d\n", pivotInteger(1)); // expect: 1 + printf("%d\n", pivotInteger(4)); // expect: -1 +} |