You have a totalof n coins that you want to form in a staircase shape, where every k-th rowmust have exactly k coins.
Given n, findthe total number of full staircase rows that can be formed.
n is anon-negative integer and fits within the range of a 32-bit signed integer.
Example 1:
n = 5
The coins canform the following rows:
¤
¤ ¤
¤ ¤
Because the 3rdrow is incomplete, we return 2.
Example 2:
n = 8
The coins canform the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
Because the 4throw is incomplete, we return 3.
题目不难,不过提醒一点,最好用减法,不要用加法。具体代码如下:
public classSolution {
public int arrangeCoins(int n) {
int sum=0;int i=1;
int count=0;
while(n>=i){
count++;
n-=i;
i++;
}
return count;
}
}