[HackerRank] Counter game

JAMM·2023년 3월 18일
0

HackerRank

목록 보기
3/7
post-thumbnail

Problem

Code

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'counterGame' function below.
#
# The function is expected to return a STRING.
# The function accepts LONG_INTEGER n as parameter.
#

def counterGame(n):
    # Write your code here
    cnt = 0
    '''
    Step 1.
    문제에서 n의 범위는 1 <= n <= (2 ** 64) - 1로 정의했기 때문에,
    2의 제곱에 대한 리스트 생성
    '''
    two_power_list = list(2 ** i for i in range(65))
    
    while True:
    	'''
        Step 2.
        n의 값이 1일 때, 승자가 결정
        게임 횟수를 cnt라는 전역 변수에 저장
        cnt를 2로 나누었을 때, 나머지가 1인 경우 승자는 Louise
        cnt를 2로 나누었을 때, 나누어지면 승자는 Richard
        '''
        if n == 1:
            return 'Louise' if cnt % 2 == 1 else 'Richard'
        
        '''
        Step 3.
        n의 값이 2의 제곱인지 판별
        '&'라는 비트 연산을 사용
        ex) n = 8
        n을 이진수로 표현할 경우, 1000
        n-1을 이진수로 표현할 경우, 111
        이 때, 1000과 111의 비트연산 결과 0000
        
        따라서, n & (n-1)의 결과가 0이 아닌 경우
        즉, n이 2의 제곱 수가 아닌 경우
        n보다 작은 2의 제곱수를 n에서 빼준다.
        
        n & (n-1)의 결과가 0인 경우
        즉, n이 2의 제곱 수일 때
        n을 2로 나눠준다.
        '''
        if (n & (n-1)):
            for idx, x in enumerate(two_power_list):
                if n < x:
                    n -= two_power_list[idx-1]
                    break
        else:
            n = n // 2
        
        cnt += 1

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input().strip())

    for t_itr in range(t):
        n = int(input().strip())

        result = counterGame(n)

        fptr.write(result + '\n')

    fptr.close()

Reference

HackerRank - Counter game
2의 n제곱 판별

0개의 댓글