Arranging Coins
Arranging Coins

Arranging Coins
• 发表于 4个月前
• 阅读 11
• 收藏 0
• 评论 0

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.

Example 1:

```n = 5
The coins can form the following rows:
¤
¤ ¤
¤ ¤
Because the 3rd row is incomplete, we return 2.```

Example 2:

```n = 8
The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
Because the 4th row is incomplete, we return 3.```

① 按照第i行会有i个硬币分配，当n<0时，停止计数即可。55ms

public class Solution {
public int arrangeCoins(int n) {
int i = 1;
int count = 0;
while(n > 0){
n = n - i;
i ++;
if(n >= 0){
count ++;
}
}
return count;
}
}
② 采用折半查找的方式：46ms

1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + x <= n

public class Solution {
public int arrangeCoins(int n) {
int start = 0;
int end = n;
while (start <= end){
int mid = (end - start) / 2 + start; //(end - start) / 2 + start  VS  (start + end) >>> 1
if ((0.5 * mid * mid + 0.5 * mid ) <= n){//公式
start = mid + 1;
}else{
end = mid - 1;
}

}
return start - 1;
}
}

③ 利用一元二次方程求根的数学方法求解：47ms

1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + x <= n

x = 1 / 2 * (-sqrt(8 * n + 1)-1)（为负数，不符合题意）

public class Solution {
public int arrangeCoins(int n) {//(int)((sqrt(1 + 8 * (long)n)-1) / 2)
return (int) ((Math.sqrt(1 + 8.0 * n) - 1) / 2);// java会将中间结果自动装箱为long型数据
}
}

×