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);
}
- 내 풀이에서 더 줄일 수 있다. if else를 안쓰고 그냥 바로바로 2로 나눈 나머지를 더하고 2로 나눈다.
2.C++에서 마련해주는 stl과는 또 다른, gcc compiler 자체의 builtin 함수들이 몇개 있습니다. 저 함수는 비트단위로 1의 개수를 셉니다.
그런 함수가 있다고한다.