2016年11月19日 星期六

[LeetCode] 441. Arranging Coins

轉自LeetCode

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.
<Solution>

這題是數學題

梯形每個梯數的長度總和,就是差為1的等差級數的和

公式為 x(x + 1) / 2

所以這題答案就是在解 x^2 + x - 2n <= 0

用一元二次公式解 : x = (-b +/- sqrt(b^2 - 4ac)) / 2a

因為答案不會有負的,所以最後的算式就是

x =  sqrt(2*n + 0.25) - 0.5

最後會將答案 cast 成 int,預設就是無條件捨去,所以符合 <= 0 的算式

沒有留言:

張貼留言