设为首页 加入收藏

TOP

LeetCode―Reverse Bits ,1 Bit和数字的二进制情况相关
2015-11-21 01:05:01 来源: 作者: 【 】 浏览:3
Tags:LeetCode Reverse Bits Bit 数字 二进制 情况 相关

?

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).

简单的做法就是遍历一遍,但是这个方法很低效,貌似也没有什么更好的办法了

?

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        if(0 == n)
        {
            return 0;
        }
        int res = 0;
        for(int i = 0; i < 32; i++)
        {
            if( n & 1)
            {
                res += (1 << (31-i));
            }
            n = n >> 1;
        }
        return res;
    }
};

?

?

Number of 1 Bits

?

?

?

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

这里注意 n&(n-1)可以将最后一个1消掉,所以不用全部遍历一遍,有多少个1,就循环多少次

?

?

?

class Solution {
public:
    int hammingWeight(uint32_t n) {
        if(0 == n)
        {
            return 0;
        }
        int res = 0;
        while(n)
        {
            n = n&(n-1);
            res++;
        }
        return res;
    }
};


?

?

Reverse Integer

?

?

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321 这里计算过程并不复杂,但是注意是否会超过范围

?

class Solution {
public:
    int reverse(int x) {
        long long xx = x; //防止负数超过范文
        if(0 == x)
        {
            return 0;
        }
        int flag = 0;
        if(x < 0)
        {
            flag = 1;
            xx = -x;
        }
        stack
  
    temp;
        while(xx)
        {
            temp.push(xx%10);
            xx = xx/10;
        }
        long long index = 1;
        long long res = 0;
        while(!temp.empty())
        {
            res += temp.top()*index;
            index = index*10;
            temp.pop();
        }
        if(flag)
        {
            res = res*(-1);
            if(res < INT_MIN)
            return 0;
        }
        if(res > INT_MAX)
        {
            return 0;
        }
        return res;
    }
};
  


?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇ZOJ3860:Find the Spy 下一篇ZOJ3864:Quiz for EXO-L(BFS)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: