Machineboy空

Excercism - Secret Handshake 2진수 변환, 비트연산자(&,>>) 본문

Computer/Coding Test

Excercism - Secret Handshake 2진수 변환, 비트연산자(&,>>)

안녕도라 2025. 2. 5. 13:02

문제요약

1~ 31까지의 10진수를 입력하면, 2진수로 바꾼 뒤 숫자에 맞는 동작을 수행하라.

https://exercism.org/tracks/csharp/exercises/secret-handshake

 

Secret Handshake in C# on Exercism

Can you solve Secret Handshake in C#? Improve your C# skills with support from our world-class team of mentors.

exercism.org


난이도

Easy


풀이 포인트

  • 2진수 변환
// 내가 구현한 2진법 변환

string binary = "";
int num;

while(num > 0)
{
    binary = (num % 2) + binary;
    num /= 2;
}
// GPT 풀이: << shift 연산자, & 비트연산자
// 바로 해당 비트가 켜져있는지를 확인

for(int i = 0; i < actions.Length; i++)
{
	if((commandValue & (1 << i)) != 0)
    {
    	answer.Add(actions[i]);
    }
}

REVIEW

 

나는 10진수를 2진수로 변환할 때, 

10진수를 2로 나누고, 나머지를 string값에 축적하는 방식으로 구현했다.

 

GPT는 1을 shift 연산자를 이용해 한 칸씩 이동하며 바로 10진수와 비교하며, 해당 비트가 켜져있는지를 확인하는 방식으로 구현했다.

2진수를 다룰 때, 비트연산자를 활용하면 코드의 품질을 높일 수 있군!


CODE

using System;
using System.Collections.Generic;

public static class SecretHandshake
{
    public static string[] Commands(int commandValue)
    {
        List<string> answer = new List<string>();
        string[] actions = new string[] { "wink", "double blink", "close your eyes", "jump" };

        // 5번째 비트는 동작 순서 반전 여부를 결정
        bool shouldReverse = (commandValue & 16) != 0;

        // 첫 4비트에 해당하는 동작 추가
        for (int i = 0; i < actions.Length; i++)
        {
            if ((commandValue & (1 << i)) != 0)
            {
                answer.Add(actions[i]);
            }
        }

        if (shouldReverse)
        {
            answer.Reverse();
        }

        return answer.ToArray();
    }
}

 

using System;
using System.Collections.Generic;

// 서로를 모른다.
// 악수를 하면 멤버인지 알 수 있다.
// 1~31 중 하나를 말하면 그 숫자에 해당하는 action을 해야한다.

public static class SecretHandshake
{
    static List<string> answer = new List<string>();
    static string binary = "";
    static string[] actions = new string[] {"wink", "double blink", "close your eyes", "jump"};

    public static string[] Commands(int commandValue)
    {
        answer.Clear(); // 리스트 초기화
        binary = "";    // 이진수 문자열 초기화
        int num = commandValue;

        // 10진수 > 2진수
        while (num > 0)
        {
            binary = (num % 2) + binary;
            num /= 2;
        }

        // 5비트로 맞추기
        while (binary.Length < 5)
        {
            binary = '0' + binary;
        }
        Console.WriteLine(binary);

        // 동작 추가 (오른쪽에서 왼쪽으로 읽기)
        for (int i = 0; i < 4; i++) // 0~3 인덱스 (가장 오른쪽 비트부터)
        {
            if (binary[binary.Length - 1 - i] == '1') // 오른쪽 끝부터 검사
            {
                answer.Add(actions[i]); // 인덱스에 맞는 액션 추가
            }
        }

        // 5번째 비트(가장 왼쪽 비트)가 1이면 순서 반전
        if (binary[0] == '1')
        {
            answer.Reverse();
        }

        return answer.ToArray();
    }
}