难度简单182收藏分享切换为中文接收动态反馈
You have
n
coins and you want to build a staircase with these coins. The staircase consists ofk
rows where theith
row has exactlyi
coins. The last row of the staircase may be incomplete.Given the integer
n
, return the number of complete rows of the staircase you will build.你总共有 n 枚硬币,并计划将它们按阶梯状排列。对于一个由 k 行组成的阶梯,其第 i 行必须正好有 i 枚硬币。阶梯的最后一行 可能 是不完整的。
给你一个数字 n ,计算并返回可形成 完整阶梯行 的总行数。
Example 1:
Input: n = 5 Output: 2 Explanation: Because the 3rd row is incomplete, we return 2.Example 2:
Input: n = 8 Output: 3 Explanation: Because the 4th row is incomplete, we return 3.
class Solution {
public int arrangeCoins(int n) {
long left = 0;
long right = n;
long k,curr;
while(left <= right){
k = left + (right - left) / 2;
//计算层数所有的硬币值
curr = k * (k + 1) / 2;
if(n == curr) return (int)k;
if(n < curr){
right = k - 1;
} else {
left = k + 1;
}
}
return (int)right;
}
}