zoukankan      html  css  js  c++  java
  • OJ练习37——T190 Reverse Bits

    把一个32位无符号整数按位翻转,

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

    【思路】

    可以首尾位交换,使用位运算和移位运算。

    但是有个棘手的地方,想要把低位变成不能使用&(高位移位),因为如果高位是1,低位是0,结果就是0,不等于高位;

    如果使用|(高位移位),又会有高位是0,低位是1,结果还是不等于高位。所以不能单单使用位运算。

    【my code】

    uint32_t reverseBits(uint32_t n) {
            uint32_t temp1,temp2,low,high,dis;
            high=0x80000000;
            low=0x1;
            dis=31;
            while(low<high){
                temp1=high & n;
                temp2=low & n;
                if(temp1!=temp2){
                if(temp2&&!temp1){
                    n+=high;
                    n-=low;
                }
                else if(!temp2&&temp1){
                    n+=low;
                    n-=high;
                }
                }
                high>>=1;
                low<<=1;
                dis--;
            }
            return n;
        }

    【反思】

    对于位运算一直都很不熟练,对于位的交换纠结了很久。看起来不是个聪明的做法。

    耗时9ms,排名在c的效率范围。

    【other code】

    uint32_t reverseBits(uint32_t n) {
        uint32_t answer;
        uint32_t i;
        
        answer = 0;
        
        /*把一个unsigned int 数字1一直左移,直到它变成全0的时候,也就得到了该机器内unsigned int的长度*/
        for (i = 1; i != 0; i <<= 1)
        {
            answer <<= 1;
            if (n & 1) { answer |= 1; }
            n >>= 1;
        }
        
        return answer;
        }

    【评价】

    该法“新开了空间”,不过也只是一个无符号整数大小,微不足道,人家代码是很简洁的。

    妙处在于for循环中,i!=0的条件,i左移,直到溢出为0.这就遍历了要求的位数(这里倒是不必要,已知32)。

    耗时10ms,排名和我的算法一样。

    所以说,总是有更优秀的算法。

  • 相关阅读:
    模拟展示动态按钮
    模拟界面请求到web服务器
    bean的生命周期
    structs2的action实现方式
    annotation中的Autowired
    华为笔试题练习
    开发工具
    [转]Linux双向链表的知识
    【转】 嵌入式C语言编程中Inline函数的应用
    打印格式化printf
  • 原文地址:https://www.cnblogs.com/ketchups-notes/p/4468090.html
Copyright © 2011-2022 走看看