We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 04b7792 commit 4f0cefeCopy full SHA for 4f0cefe
Easy/Arranging Coins.java
@@ -1,14 +1,18 @@
1
class Solution {
2
public int arrangeCoins(int n) {
3
- int copy = n;
4
- int count = 0;
5
- for (int i = 1; i <= copy && n > 0; i++) {
6
- n -= i;
7
- if (n < 0) {
8
- break;
+ long left = 1;
+ long right = n;
+ while (left <= right) {
+ long mid = (left + right) / 2;
+ long sum = mid * (mid + 1) / 2;
+ if (sum == n) {
9
+ return (int) mid;
10
+ } else if (sum > n) {
11
+ right = mid - 1;
12
+ } else {
13
+ left = mid + 1;
14
}
- count++;
15
- return count;
16
+ return (int) right;
17
18
0 commit comments