你总共有 n 枚硬币,你需要将它们摆成一个阶梯形状,第 k 行就必须正好有 k 枚硬币。
给定一个数字 n,找出可形成完整阶梯行的总行数。
n 是一个非负整数,并且在32位有符号整型的范围内。
示例 1:
n = 5
硬币可排列成以下几行:
¤
¤ ¤
¤ ¤
因为第三行不完整,所以返回2.
示例 2:
n = 8
硬币可排列成以下几行:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
因为第四行不完整,所以返回3.
我的代码,其实可以用等差数列来进行运算
class Solution {
public int arrangeCoins(int n) {
if(n == 1 || n== 2){
return 1;
}else {
int count = 0;
int s = 1;
while (n >= 0 ) {
n =n-s;
count++;
s++;
}
return count-1;
}
}
}
又是一个跟数学有关的题目,一开始打算用等差数列的公式来的,但是可能会出现溢出,后来一想溢出的话也只有为负数了因此将判定条件增加一个
即可通过啦
class Solution {
public int arrangeCoins(int n) {
int count = 0;
while (true) {
count ++;
if((1+count)%2==0){
if((((1+count)/2)*count) <= n && (((1+count)/2)*count) > 0){
// System.out.println(((1+count)*count) / 2);
//count++;
}else {
return count-1;
}
}else {
if(((count/2)*(1+count)) <= n && ((count/2)*(1+count)) > 0 ){
// System.out.println(((1+count)*count) / 2);
//count++;
}else {
return count-1;
}
}
}
}
}
排名靠前的,不得不说这样很高
class Solution {
public int arrangeCoins(int n) {
return (int) (Math.sqrt(2*(long)n+0.25) - 0.5);
}
}