문제 설명
숫자가 주어지면 극단 위치, 즉 첫 번째와 마지막 위치, 두 번째와 두 번째 마지막 위치 등에서 비트를 교환하여 최대화합니다.
입력 숫자가 8이면 이진 표현은 -
00000000 00000000 00000000 00001000
극단 위치에서 비트를 교환한 후 number는 -
가 됩니다.00010000 00000000 00000000 00000000 and its decimal equivalent is: 268435456
알고리즘
1. Create a copy of the original number 2. If less significant bit is 1 and more significant bit is 0 then swap the bits in the bit from only, continue the process until less significant bit’s position is less than more significant bit’s position 3. Return new number
예시
#include <bits/stdc++.h>
#define ull unsigned long long
using namespace std;
ull getMaxNumber(ull num){
ull origNum = num;
int bitCnt = sizeof(ull) * 8 - 1;
int cnt = 0;
for(cnt = 0; cnt < bitCnt; ++cnt, --bitCnt) {
int m = (origNum >> cnt) & 1;
int n = (origNum >> bitCnt) & 1;
if (m > n) {
int x = (1 << cnt | 1 << bitCnt);
num = num ^ x;
}
}
return num;
}
int main(){
ull num = 8;
cout << "Maximum number = " << getMaxNumber(num) << endl;
return 0;
} 출력
위의 프로그램을 컴파일하고 실행할 때. 다음 출력을 생성합니다 -
Maximum number = 268435456