Arranging Coins
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:
|
|
Example 2:
|
|
提示 | 解題應用 |
---|---|
Math | 規律觀查 |
Default:
|
|
解答思路:
很單純的題目,只要不斷將n減去一連續數列(1,2,3…),當n小於0時其減去該數的前一個值就是最大能完成的列數。
程式碼解說:
因為要減去的數列是從1開始,所以先初始化數列起始值為1,接著開始不斷利用迴圈將n與連續數列做相減,而數列的值也依續不斷變大,直到n減去該值時小於0才停止,而因為要找的是有排滿的列數,所以結果就是該數再去-1就是我們要的答案
|
|
完整程式碼:
|
|
總結:
若有一數量的硬幣照每列各有(1,2,3…)的數量排序,找出最大且該列能排滿的位置,只要不斷將n減去一連續數列(1,2,3…),當n小於0時其減去該數的前一個值就是最大能完成的列數。