본문 바로가기

Programming/Algorithm

[Codewars] Double Cola 문제 풀이 C# 코딩테스트

반응형

 

개인적으로 좋아하는 미드 빅뱅이론 주인공들이 나온 문제

 

문제
더보기

Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on.

For example, Penny drinks the third can of cola and the queue will look like this:

Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny

Write a program that will return the name of the person who will drink the n-th cola.

 

 

풀이
public string WhoIsNext(string[] names, long n)
{
    long length = names.Length;
    long generation = 1;

    while (n > length)
    {
        n -= length;
        length *= 2;
        generation *= 2;
    }

    return (names[(n - 1) / generation]);
}

 

문제 링크 : https://www.codewars.com/kata/551dd1f424b7a4cdae0001f0/train/csharp

반응형