카테고리 없음
Excercism - Eliud's Eggs 이진법, 10진법
안녕도라
2025. 1. 16. 18:42
문제요약
10진수가 주어지면, 2진수로 바꾸어 1의 개수를 구하여라.
https://exercism.org/tracks/csharp/exercises/eliuds-eggs/iterations
Exercism
Learn, practice and get world-class mentoring in over 50 languages. 100% free.
exercism.org
난이도
Easy
풀이 포인트
- 2진법 <-> 10진법 변환
- while문
REVIEW
너무 간단한 수학 문제인데 헤맸다.
10진법을 2진법으로 만드는 원리를 까먹었다.
이럴땐 써보면서 원리 파악한 후에 코드 짜야 하는데 마음이 급했다.
CODE
public static class EliudsEggs
{
public static int EggCount(int encodedCount)
{
int answer = 0;
// 2진수 변환하며 1의 개수 세기
while (encodedCount > 0)
{
// 현재 숫자가 2로 나눴을 때 나머지가 1이면, 이는 비트가 1임을 의미
if (encodedCount % 2 == 1)
{
answer++;
}
// 숫자를 2로 나눔
encodedCount /= 2;
}
return answer;
}
}