2017年5月1日 星期一

[LeetCode] 190. Reverse Bits

轉自LeetCode

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 如下


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;
}
};
view raw reverseBits.cpp hosted with ❤ by GitHub

Kotlin
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
}
}
view raw reverse_bits.kt hosted with ❤ by GitHub

沒有留言:

張貼留言