劍指offer-java

來源:互聯網
上載者:User

標籤:open   題意   面試官   取反   ges   indicator   sed   image   function   

leetcode 191. 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.

解法:

1.普通解法:利用1的移位相與

 1 public class Solution { 2     // you need to treat n as an unsigned value 3     public int hammingWeight(int n) { 4         int flag = 1; 5         int count = 0; 6         while (flag != 0) { 7             if ((n & flag) != 0) { 8                 count++; 9             }10             flag = flag << 1;11         }12         return count;13     }14 }
View Code

2.能給面試官打來驚喜的解法,p80 利用減1的性質:減1其實是把最右邊的一個1之後的位取反,再與原數字相與就只剩下了前面的位。

 1 public class Solution { 2     // you need to treat n as an unsigned value 3     public int hammingWeight(int n) { 4         int count = 0; 5         while (n != 0) { 6             count++; 7             n = n & (n - 1); 8         } 9         return count;10     }11 }
View Code

 

劍指offer-java

聯繫我們

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