LeetCode—Reverse Bits ,1 Bit和數位二進位情況相關,leetcodereverse

來源:互聯網
上載者:User

LeetCode—Reverse Bits ,1 Bit和數位二進位情況相關,leetcodereverse

https://leetcode.com/problems/reverse-bits/

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 

https://leetcode.com/problems/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 

https://leetcode.com/problems/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<int> 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;    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.