문제를 푼 날: 2022년 11월 13일 오후 2:40 (GMT+9)
https://leetcode.com/problems/reverse-bits/
Reverse bits of a given 32 bits unsigned integer.
Note:
-3 and the output represents the signed integer 1073741825.Example 1:
Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation:The input binary string00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is00111001011110000010100101000000.
Example 2:
Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation:The input binary string11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is10111111111111111111111111111111.
Constraints:
32Follow up: If this function is called many times, how would you optimize it?
일단은 생각나는 대로 풀었는데, 왜 음수인 경우에는 1을 추가로 더해야 하는지는 잘 모르겠다.
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ret = 0;
uint32_t isMinus = (n & (1<<31));
for(int i=0;i<31;++i){
ret |= (n & 1);
ret <<= 1;
n >>= 1;
}
if(isMinus) ++ret;
return ret;
}
};