Created
November 9, 2018 04:13
-
-
Save ilyasfoo/79d0f2001334827eeb69e0e128b1a07a to your computer and use it in GitHub Desktop.
Python 3 solution for https://leetcode.com/problems/elimination-game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def lastRemaining(self, n): | |
""" | |
:type n: int | |
:rtype: int | |
""" | |
odd = True | |
remainder = n | |
startNum = 1 | |
power = 1 | |
while remainder > 1: | |
if remainder == 2: | |
return startNum+power if odd else startNum | |
elif remainder == 3: | |
return startNum+power | |
# startNum increases only by 2 case, if the remainder is odd OR if the step is odd | |
startNum += power if remainder % 2 == 1 or odd else 0 | |
power *= 2 | |
# Divide by 2 and floor | |
remainder //= 2 | |
odd = not odd | |
# n == 1 returns 1 | |
return 1 |
Author
ilyasfoo
commented
Nov 9, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment