[266가지 문제로 정복하는 코딩 인터뷰] 나만의 문제 풀이 <Chapter 4>

rhkr9080·2023년 1월 23일
0

4-1. parity

#include <iostream>
#include <bitset>

using namespace std;

short Parity(unsigned long long x) {
	short result = 0;
	while(x) {
		result ^= (x & 1);
		x >>= 1;
	}
	return result;
}

short cpyLSB(unsigned long long x) {
	return x | (x-1);
}

int getModPowerofTwo(unsigned long long x) {
	unsigned long long orig = x;
	if (x == 0)
		return 0;
	int MSB = 0;
	x >>= 1;
	while (x)
	{
		x >>= 1;
		MSB++;
	}
	return orig - (1 << MSB);
}

int checkPowerofTwo(unsigned long long x) {
	if (x & (x - 1))
		return 0;
	else
		return 1;
}

int main()
{
	int num = 0;

	//cout << Parity(101010);
	cout << bitset<8>(0b01010000) << endl;
	cout << bitset<8>(cpyLSB(0b01010000)) << endl;
	cout << bitset<8>(77) << endl;
	cout << getModPowerofTwo(77) << endl;
	cout << checkPowerofTwo(77) << endl;
	cout << checkPowerofTwo(64) << endl;

	return (0);
}
profile
공부방

0개의 댓글