首页 > 其他 > 详细

LeetCode - Refresh - Reverse Bits

时间:2015-03-23 07:04:41      阅读:237      评论:0      收藏:0      [点我收藏+]

Two method of making that:

1. As we know this is 32 bit integer. We just get the bit and shift to 31 - i. 

 1 class Solution {
 2 public:
 3     uint32_t reverseBits(uint32_t n) {
 4         uint32_t result;
 5         for (int i = 0; i < 32; i++) {
 6             result |= ((n >> i) & 1) << (31 - i);
 7         }
 8         return result;
 9     }
10 };

 

2. Swap bits

 1 class Solution {
 2 public:
 3     uint32_t swapBits(uint32_t n, int i, int j) {
 4         int first = (n >> i) & 1, second = (n >> j) & 1;
 5         if (first ^ second) {
 6             n ^= (1U << i) | (1U << j);
 7         }
 8         return n;
 9     }
10     uint32_t reverseBits(uint32_t n) {
11         for (int i = 0; i < 16; i++) {
12             n = swapBits(n, i, 31-i);
13         }
14         return n;
15     }
16 };

 

LeetCode - Refresh - Reverse Bits

原文:http://www.cnblogs.com/shuashuashua/p/4358819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!