Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 숫자에 동일한 수의 설정 및 설정되지 않은 비트가 있는지 확인하십시오.

<시간/>

이 섹션에서는 숫자가 동일한 수의 설정 비트와 설정되지 않은 비트를 갖는지 여부를 확인합니다. 숫자 12가 있다고 가정합니다. 바이너리 표현은 1100입니다. 이것은 0과 1의 수가 같습니다.

접근 방식은 간단합니다. 숫자의 각 비트를 확인하고 1이면 set_bit_count를 늘리고 0이면 unset_bit_count를 늘립니다. 마지막으로 동일하면 true를 반환하고 그렇지 않으면 false를 반환합니다.

예시

#include <iostream>
using namespace std;
bool hasSameSetUnset(int n) {
   int set_count = 0, unset_count = 0;
   while(n){
      if((n & 1) == 1){
         set_count++;
      }else{
         unset_count++;
      }
      n = n >> 1; //shift to right
   }
   if(set_count == unset_count)
   return true;
   return false;
}
int main() {
   int num = 35; //100011
   if(hasSameSetUnset(num)){
      cout << "Has same set, unset bits";
   }else{
      cout << "Not same number of set, unset bits";
   }
}

출력

Has same set, unset bits