Java位元運算總結-leetcode題目

來源:互聯網
上載者:User

標籤:

按位操作符只能用於整數基礎資料型別 (Elementary Data Type)中的單個bit中,操作符對應表格:

Operator Description
& 按位與(12345&1=1,可用於判斷整數的奇偶性)
| 按位或
^ 異或(同假異真)
~ 非(一元操作符)
&=,|=,^= 合并運算和賦值
<<N 左移N位,低位補0
>>N 右移N位,(正數:高位補0,負數高位補1)
>>>N 無符號右移(無論正負數,高位皆補0)
<<=,>>=,>>>= 合并運算和賦值(移動相應位元再賦值給左邊變數)

leetcode191:

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.

值得注意的是我們要將傳入的int n作為不帶正負號的整數看待,但是在java中int是有符號的,我想到的方法就是利用上面的>>>無符號移位操作,代碼如下:

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        int num = 0;        do{            if((n & 1) == 1) num++;        }while((n>>>=1) > 0);        return num;    }        public static void main(String[] args){        System.out.println((new Solution()).hammingWeight(11));    }}

 

leetcode190:

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

Follow up:
If this function is called many times, how would you optimize it?

二進位的倒置可以用移位來進行,增加運算效率

1     public int reverseBits(int n) {2         int rs = 0;3         for (int i = 0; i < 32; i++) {4             rs = (rs << 1) + (n & 1);5             n >>= 1;6         }7         return rs;8     }

 

leetcode7:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

十進位的倒置同樣值得注意的就是倒置以後溢出的問題,我採用的方法就是函數內利用Long類型來進行計算,並在轉換成int前與intMax進行比較,如果溢出返回0(題目要求)

 1     public int reverse(int x) { 2         long l = new Long(x); 3         Long tmp = 0L; 4         while (l != 0) { 5             tmp = tmp * 10 + l % 10L; 6             l /= 10; 7         } 8         if (x > 0 && tmp > 2147483647L || x < 0 && tmp < -2147483648) 9             return 0;10         return tmp.intValue();11     }

 

想到了新的解法再更新

 

Java位元運算總結-leetcode題目

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.