原题链接
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.
思路:显然等差数列求和,要解的方程为:
k?(k+1))2?n k ? ( k + 1 ) ) 2 ? n
解出k的范围为:
k??1+1+8n??????√2 k ? ? 1 + 1 + 8 n 2
计算后边式子的值取整即可,注意8n可能会超过int范围,需要向上转换。
AC代码:
class Solution {
public:int arrangeCoins(int n) {return (int)((sqrt(1+8.0*n)-1)/2.0);}
};