File tree 2 files changed +85
-0
lines changed
2 files changed +85
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 문제
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.
3
+
4
+ Given n, find the total number of full staircase rows that can be formed.
5
+
6
+ n is a non-negative integer and fits within the range of a 32-bit signed integer.
7
+
8
+ ```
9
+ Example 1:
10
+
11
+ n = 5
12
+
13
+ The coins can form the following rows:
14
+ ¤
15
+ ¤ ¤
16
+ ¤ ¤
17
+
18
+ Because the 3rd row is incomplete, we return 2.
19
+ Example 2:
20
+
21
+ n = 8
22
+
23
+ The coins can form the following rows:
24
+ ¤
25
+ ¤ ¤
26
+ ¤ ¤ ¤
27
+ ¤ ¤
28
+
29
+ Because the 4th row is incomplete, we return 3.
30
+ ```
31
+
32
+ ### 솔루션
33
+ n 이라는 수가 들어왔을 때 1씩 증가하는 수열 ` a + (a+1) + (a+2) + ... + (a+k) <= n ` 에서 만족하는 ` k ` 를 찾는 문제였다.
34
+ 이를 수식으로 풀면 된다.
35
+
36
+ #### 해결 1
37
+ 1씩 증가하는 수열의 합은 (고등학생 때 다들 배웠겠지만...) ` k * (k+1) / 2 ` 이니까 이 값이 주어진 값 n 을 안넘게 하는 k 를 찾으면 된다.
38
+ 코드에서 이 k 값은 a 이고 k * (k+1) 은 b 로 두고 while 문을 돌렸다.
39
+
40
+ ``` python3
41
+ class Solution :
42
+ def arrangeCoins (self , n : int ) -> int :
43
+
44
+ a = 1
45
+ b = 2
46
+ while b <= (2 * n):
47
+ a += 1
48
+ b = (pow (a, 2 ) + a)
49
+
50
+ return a - 1
51
+ ```
52
+
53
+ #### 해결 2
54
+ 이 코드도 돌아가지만 결국 공식은 ` k * (k+1) / 2 <= 2 * n ` 이므로 n 은 알고 있으니까 k를 변수로 두고 식을 풀어쓸 수도 있다.
55
+ k를 대상으로 완전 제곱식을 만들면 된다. 이 때 만족하는 k 는 정수인데, sqrt 해서 나온 결과 값은 float 이므로 int 로 캐스팅 해준다.
56
+ (캐스팅 해주는 이유는 위의 코드에서 -1 하는 것과 같음)
57
+
58
+ ``` python3
59
+ class Solution :
60
+ def arrangeCoins (self , n : int ) -> int :
61
+ return int (sqrt((2 * n) + 0.25 ) - 0.5 )
62
+ ```
63
+
64
+ 이 방법의 경우 수학 공식이기 때문에 해결 1 보다 훨씬 빠르다.
Original file line number Diff line number Diff line change
1
+ from math import sqrt
2
+
3
+
4
+ class Solution :
5
+ def arrangeCoinsWithWhile (self , n : int ) -> int :
6
+ a = 1
7
+ b = 2
8
+ while b <= (2 * n ):
9
+ a += 1
10
+ b = (pow (a , 2 ) + a )
11
+
12
+ return a - 1
13
+
14
+ def arrangeCoinsWithMath (self , n : int ) -> int :
15
+ return int (sqrt ((2 * n ) + 0.25 ) - 0.5 )
16
+
17
+
18
+ if __name__ == '__main__' :
19
+ sol = Solution ()
20
+ print (sol .arrangeCoinsWithMath (8 ))
21
+ print (sol .arrangeCoinsWithMath (5 ))
You can’t perform that action at this time.
0 commit comments