[프로그래머스/C++]Lv.2 - 점프와 순간이동

YH J·2023년 6월 29일
0

프로그래머스

목록 보기
139/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/12980

내 풀이

n을 분해해간다. n이 짝수면 2로 나누고, 홀수면 1을 뺀다.
1을 뺀 횟수를 기록해서 리턴한다.

내 코드

#include <iostream>
using namespace std;

int solution(int n)
{
    int ans = 0;
    while(n > 0)
    {
        if(n % 2)
        {
            ans++;
            n--;
        }
        else
            n /= 2;
    }
    return ans;
}

다른 사람의 풀이

1.
#include <iostream>
using namespace std;

int solution(int n)
{
    int ans = 0;
    while(n >0)
    {
        ans += n%2;
        n /=2;
    }

    return ans;
}

2.
#include <iostream>
using namespace std;

int solution(int n)
{
    return __builtin_popcount(n);
}

다른 사람의 풀이 해석

  1. 내 풀이에서 더 줄일 수 있다. if else를 안쓰고 그냥 바로바로 2로 나눈 나머지를 더하고 2로 나눈다.

2.C++에서 마련해주는 stl과는 또 다른, gcc compiler 자체의 builtin 함수들이 몇개 있습니다. 저 함수는 비트단위로 1의 개수를 셉니다.
그런 함수가 있다고한다.

profile
게임 개발자 지망생

0개의 댓글