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,排名和我的算法一样。

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

  • 相关阅读:
    LeetCode 226. Invert Binary Tree
    LeetCode 221. Maximal Square
    LeetCode 217. Contains Duplicate
    LeetCode 206. Reverse Linked List
    LeetCode 213. House Robber II
    LeetCode 198. House Robber
    LeetCode 188. Best Time to Buy and Sell Stock IV (stock problem)
    LeetCode 171. Excel Sheet Column Number
    LeetCode 169. Majority Element
    运维工程师常见面试题
  • 原文地址:https://www.cnblogs.com/ketchups-notes/p/4468090.html
Copyright © 2011-2022 走看看