LeetCode 第 190 題 (Reverse Bits)
LeetCode 第 190 題 (Reverse Bits)
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
將一個整數按位翻轉,題目並不難。最簡單的辦法就是用個迴圈遍歷各個位,然後將其放置到合適的位置。下面是程式碼:
uint32_t reverseBits(uint32_t n)
{
uint32_t ret = 0;
for(int i = 0; i < 32; i++)
{
ret = (ret << 1) + (n & 1);
n = n >> 1;
}
return ret;
}
這裡需要注意的是運算子的優先順序, “<<” 和 “&” 的優先順序都很低,所以要加括號,這個地方很容易出錯。
除了這種迴圈置位方法,還可以用查表法。我們沒法將 32 位整數列舉一遍,但是可以列舉小一點的整數。比如下面程式這樣四位四位的處理。
class Solution {
public:
uint8_t reverseChar(uint8_t c)
{
const uint8_t table[16] = {0x0, 0x8, 0x4, 0xC, 0x2, 0xA, 0x6, 0xE, 0x1, 0x9, 0x5, 0xD, 0x3, 0xB, 0x7, 0xF};
return (table[c & 0xF] << 4) + table[c >> 4];
}
uint32_t reverseBits(uint32_t n) {
uint8_t * p = (uint8_t *)&n;
uint32_t ret;
uint8_t * q = (uint8_t *) &ret;
q[0] = reverseChar(p[3]);
q[1] = reverseChar(p[2]);
q[2] = reverseChar(p[1]);
q[3] = reverseChar(p[0]);
return ret;
}
};
相關文章
- leetcode刷題--Reverse BitsLeetCode
- LeetCode-Reverse BitsLeetCode
- LeetCode 第 7 題(Reverse Integer)LeetCode
- LeetCode 第 191 題 (Number of 1 Bits)LeetCode
- LeetCode 第 338 題 (Counting Bits)LeetCode
- leetcode刷題--Number of 1 BitsLeetCode
- leetcode刷題--Reverse Linked ListLeetCode
- LeetCode-Count BitsLeetCode
- LeetCode - 解題筆記 - 7 - Reverse IntegerLeetCode筆記
- LeetCode 之 JavaScript 解答第150題 —— 逆波蘭表示式求值(Evaluate Reverse Polish Notation)LeetCodeJavaScript
- leetcode Reverse IntegerLeetCode
- Leetcode171-190刷題筆記(非困難題)LeetCode筆記
- 【LeetCode】Counting Bits(338)LeetCode
- LeetCode 338 Counting BitsLeetCode
- Leetcode 7 Reverse IntegerLeetCode
- Reverse Integer leetcode javaLeetCodeJava
- [LeetCode] 191. Number of 1 BitsLeetCode
- Leetcode-Problem:Reverse IntegerLeetCode
- Leetcode Reverse Words in a StringLeetCode
- Leetcode Evaluate Reverse Polish NotationLeetCode
- leetcode Reverse Words in a StringLeetCode
- leetcode [python] 【338】Counting BitsLeetCodePython
- Leetcode第1~10題LeetCode
- leetcode 344. Reverse StringLeetCode
- LeetCode-Reverse Vowels of a StringLeetCode
- LeetCode-Reverse Words in a StringLeetCode
- Leetcode Reverse Nodes in k-GroupLeetCode
- Leetcode Reverse Linked List IILeetCode
- Reverse Words in a String leetcode javaLeetCodeJava
- Evaluate Reverse Polish Notation leetcode javaLeetCodeJava
- 338. Counting Bits--LeetCode RecordLeetCode
- LeetCode題解第122題LeetCode
- LeetCode刷題之第701題LeetCode
- Leetcode 151 Reverse Words in a StringLeetCode
- Leetcode 25 Reverse Nodes in k-GroupLeetCode
- LeetCode-Reverse Words in a String IILeetCode
- Leetcode-Reverse Linked List IILeetCode
- Leetcode-Reverse Nodes in k-GroupLeetCode