最简单的想法是位运算一位一位的挪,用for循环搞定(要注意优先级和结合性的问题):
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
public class Solution { | |
// you need treat n as an unsigned value | |
public int reverseBits(int n) { | |
int result = 0; | |
for (int i = 0; i < 32; i++) { | |
result = (result << 1) + (n & 1); | |
n = n >> 1; | |
} | |
return result; | |
} | |
} |
然后看到了别人一个不用循环的解法:
https://leetcode.com/problems/reverse-bits/discuss/54741/O(1)-bit-operation-C++-solution-(8ms)
很巧妙的利用了交换的时候这种特性:abcdefgh -> efghabcd -> ghefcdab -> hgfedcba 好困啊,只好用简单题交差啦 ~( ̄▽ ̄~)(~ ̄▽ ̄)~
没有评论:
发表评论