Leet Code OJ 191. Number of 1 Bits [Difficulty: Easy]
題目:
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’的數量(也被稱為漢明權重)。
例如,一個32位整數‘11’的二進制表示是00000000000000000000000000001011,所以函數返回3。
分析:
這道題目的考察點在于對無符號數的理解上。我們知道計算機中負數是采用補碼進行表示的,例如存儲為fffffffe的數,如果是當做無符號數,則是4294967294,如果是當做有符號數,則是-2。而Java中實際上沒有無符號數的概念的,整數都是帶符號位的。所以4294967294這個無符號數是會當做-2的,所以我們要解決的就是如何將-2(fffffffe)轉換為4294967294。首先,要想存儲4294967294,則必須使用long了,int表示不了。如果我們將-2直接轉為long會變成fffffffffffffffe,這個時候我們需要通過位運算把前面的部分清零,也就是通過“與運算”來實現。
代碼:
public class Solution {// you need to treat n as an unsigned valuepublic int hammingWeight(int n) {long nlong=n&0xFFFFFFFFL;int sum=0;while(nlong>0){if(nlong%2==1){sum++;}nlong/=2;}return sum;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 191. Number of 1 Bits [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一张大图总结数据结构与算法
- 下一篇: Leet Code OJ 1. Two