aboutsummaryrefslogtreecommitdiff
path: root/find_pivot_integer.c
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /find_pivot_integer.c
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'find_pivot_integer.c')
-rw-r--r--find_pivot_integer.c28
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
+}