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.
题目含义:给定n个硬币构造等差数列,求能构成多少行
方法一:直接遍历即可,从1开始,如果剩下是数不能构成一行则返回。注意要先判断剩下的数是否满足,而不是累加以后再判断,这样可能会导致溢出。
1 public int arrangeCoins(int n) { 2 int i=0; 3 while (n>0) 4 { 5 i++; 6 n-=i; 7 } 8 return n==0?i:i-1; 9 }
方法二:直接求根法
(x+1)*x/2 = n
x2 + x = 2n
4x2 + 4x = 8n
(2x+1)(2x+1) = 8n +1
x = (sqrt(8n+1) - 1)/2
1 public int arrangeCoins(int n) { 2 return (int)((-1.0 + Math.sqrt(1.0 + 8.0 * n)) / 2); 3 }