- Question:
You have a total of n coins that you want to form in a staircase shape, where everyk-th row must have exactlyk 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.
- Analysis:
利用二分法,我们可以计算前i行的和与n的大小关系,由此找到溢出n的边界,也就是我们需要找到的最多能排的行数。
- Code:
class Solution { public: int arrangeCoins(int n) { if (n <= 1) return n; long low = 1, high = n; while (low < high) { long mid = low + (high - low) / 2; if (mid * (mid + 1) / 2 <= n) low = mid + 1; else high = mid; } return low - 1; } };