1. 程式人生 > >Leetcode 441. Arranging Coins 硬幣放置 解題報告

Leetcode 441. Arranging Coins 硬幣放置 解題報告

1 解題思想

這道題可以理解了為給了n個硬幣,然後需要你按照這個規則:
第i層放i個硬幣

那麼,這n個硬幣,能夠完整的擺好多少層,比如說在第五層時只放了3個,那麼完整的擺了4層,輸出4

這道題直接用等差數列求和公式倒推就可以

直接看公式就可以了
/* 數學推導
假設完成K層,一共N個,由等差數列求和公式有:
(1+k)*k/2 = n
一步步推導:
k+k*k = 2*n
k*k + k + 0.25 = 2*n + 0.25
(k + 0.5) ^ 2 = 2*n +0.25
k + 0.5 = sqrt(2*n + 0.25)
k = sqrt(2*n + 0.25) - 0.5
這裡k是個浮點數,將其取為小於k的最大整數就可以
*/

2 原題

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.

3 AC解

public class Solution {
    public int arrangeCoins(int n) {
        /* 數學推導
        (1+k)*k/2 = n
        k+k*k = 2*n
        k*k + k + 0.25 = 2*n + 0.25
        (k + 0.5) ^ 2 = 2*n +0.25
        k + 0.5 = sqrt(2*n + 0.25)
        k = sqrt(2*n + 0.25) - 0.5
        */
return (int) (Math.sqrt(2*(long)n+0.25) - 0.5); } }