码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Reverse Bits

时间:2015-03-09 20:52:28      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

题目:给一个无符号的32位整数,将其二进制表示倒转过来(例如,6,二进制是110,倒过来就是011,对应的10进制整数就是3)。返回倒转之后的十进制整数。

做法很简单,对于给定的数,从最低位开始,将其分离出来,该最低位就是答案的最高位。循环32次,每次都把输入的数除以2,答案乘以2.

题目要求是程序尽可能运行快,我做了2个解法,一个用位运算来分离最后一个数,一个用取余来分离。结果出乎我的意料,取余的运算比位运算更快。

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
    uint32_t ans = 0;
    int bit = 0;
    int i = 0;
    while(i++ < 32)
    {
        bit = n % 2;//通过取余确定最后一个数是0还是1
        ans = ((ans << 1) + bit);
        n = n >> 1;
    }
    return ans;
    }
};


class Solution {
public:
uint32_t reverseBits(uint32_t n){
    uint32_t ans = 0;
    for(int i = 0; i < 32; i++)
    {
        ans <<= 1;
        ans |= (n & 1); ////通过位运算得到最后1位,并同时加上原来的数
        n >>= 1;
    }
    return ans;
}
};

 

Leetcode-Reverse Bits

标签:

原文地址:http://www.cnblogs.com/ouchengeng/p/4324435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!