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).
<Solution>按照題意,一個一個把 bit 給 reverse 即可
code 如下
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
uint32_t reverseBits(uint32_t n) { | |
uint32_t ans = 0; | |
for(int i = 0; i < 32; i++) { | |
ans |= ((n >> i) & 0x1) << (31 - i); | |
} | |
return ans; | |
} | |
}; |
Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
// you need treat n as an unsigned value | |
fun reverseBits(n:Int):Int { | |
var ans = 0 | |
for(i in 0..31) { | |
ans = ans shl 1 | |
if((n and (1 shl i)) != 0) { | |
ans = ans or 1 | |
} | |
} | |
return ans | |
} | |
} |
沒有留言:
張貼留言