Leetcode
[Bit Manipulation] 190. Reverse Bits
맑은 눈의 우사미
2023. 4. 19. 11:49
반응형
https://leetcode.com/problems/reverse-bits/
Reverse Bits - LeetCode
Can you solve this real interview question? Reverse Bits - Reverse bits of a given 32 bits unsigned integer. Note: * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed
leetcode.com
1. 개념정리
2. 코드
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
int i = 0;
while(i < 32){
result = result << 1; // or result <<= 1;
uint32_t curr = n % 2;
result += curr;
n = n >> 1; // or n >>= 1;
i++;
// cout << "result : " << bitset<32>(result) << endl;
// cout << "n : " << bitset<32>(n) << endl;
}
return result;
}
};
uint32_t를 cout으로 출력하면 2진수 값이 출력되므로
32비트 2진수 값으로 출력하고 싶으면 bitset<32>(n) 을 사용한다.
반응형