[LeetCode] #1025. Divisor Game - Python
1. ๋ฌธ์
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of:
- Choosing any x with 0 < x < N and N % x == 0.
- Replacing the number N on the chalkboard with N - x.
Also, if a player cannot make a move, they lose the game.
Return True if and only if Alice wins the game, assuming both players play optimally.
Example 1:Input: 2 Output: true Explanation: Alice chooses 1, and Bob has no more moves.
Example 2:
Input: 3 Output: false Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Note:
- 1 <= N <= 1000
2. ์์ค์ฝ๋
class Solution(object):
def divisorGame(self, N):
cnt = 0
while N!=1:
x = []
for i in range(1,N):
if N%i ==0:
x.append(i)
N = N -x[0]
cnt +=1
if cnt%2 ==0:
return False
else:
return True
3. ์์ค์ฝ๋ ์ค๋ช
Bob๊ณผ Alice๊ฐ ์น ํ์ ์ ์ด๊ฐ๋ฉฐ DivisorGame์ ํ๋ค.
N์ด๋ผ๋ ์๊ฐ ์ฃผ์ด์ง๋๋ฐ, ์ฐ๋ฆฌ๋ 0<x<N์ด๋ฉด์ N%x ==0์ธ x ๋ฅผ ์ฐพ์์ผํ๋ค.
์ฌ๊ธฐ์ x์ ํด๋นํ๋ ์๋ N์ ์ฝ์๋ค ์ค, N๋ฅผ ์ ์ธํ ๊ฒ์ด๋ผ๊ณ ์ดํดํ๋ค.
๋ฐ๋ผ์ for๋ฌธ์ 1๋ถํฐ N ์ ๊น์ง ๋๋ฉด์, ๋๋์์ ๋ 0์ด ๋๋ ์๋ค์ x ๋ฆฌ์คํธ์ ๋ฃ๋๋ค.
์ด ์ค์์ player๊ฐ ์ฒซ๋ฒ์งธ x๋ฅผ ์ ํํ๊ณ , ๊ทธ ์ ํํ x๋ฅผ N์์ ๋บ๋ค.
๊ทธ ์๊ฐ ๋ค์ N์ด ๋๋ ๊ฒ์ด๋ฏ๋ก N = N -x[0] ๋ผ๊ณ ์จ์ค๋ค.
cnt๋ก๋ ์น ํ์ ์ ๋ ํ์๋ฅผ ์นด์ดํธํ ๊ฒ์ธ๋ฐ, ์๋ก์ด N์ด ์ ๋ฐ์ดํธ ๋ ๋๋ง๋ค count ํด์ฃผ์ด์ผํ๋ฏ๋ก ๊ทธ ๋ฐ์ +1์ฐ์ฐ์๋ฅผ ์จ์ฃผ์๋ค.
Alice๊ฐ ๋จผ์ ๊ฒ์์ ์์ํ๋ ๊ฒ์ด๋ฏ๋ก, cnt๊ฐ์ด ์ง์์ผ ๋๋ false(ํจ๋ฐฐ)๋ฅผ, cnt๊ฐ์ด ํ์ ์ผ ๋๋ true(์น๋ฆฌ)๋ฅผ ๋ฐํํ๋ค.