Skip to content

Commit e737b6d

Browse files
author
iamminji
committed
[20200703] Solve july challenge questions
1 parent 33b8a86 commit e737b6d

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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 보닀 훨씬 λΉ λ₯΄λ‹€.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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))

0 commit comments

Comments
Β (0)