你总共有 n 枚硬币,你需要将它们摆成一个阶梯形状,第 k 行就必须正好有 k 枚硬币。
给定一个数字 n,找出可形成完整阶梯行的总行数。
n 是一个非负整数,并且在32位有符号整型的范围内。
来源:力扣(LeetCode)
class Solution {
public int arrangeCoins(int n) {
int i=1;
while(n>=0){
n-=i;
i++;
}
return i-2;
}
}
更快的二分查找的方法:
class Solution {
public int arrangeCoins(int n) {
long low=0,high=n;
while(low<=high){
long mid=low+(high-low)/2;
if(((1+mid)*mid)/2>n){
high=mid-1;
}else if(((1+mid)*mid)/2<n){
low=mid+1;
}else{
return (int)mid;
}
}
return (int)high;
}
}
还可以直接用等差数列求和列方程,然后用求根公式求解
class Solution {
public int arrangeCoins(int n) {
return (int)(-1+Math.sqrt(8*(long)n+1))/2;
}
}