【LeetCode从零单排】No 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 00000

题目

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


代码

1.递归运算,虽然leet不通过,因为时间原因
public class Solution {
    // you need to treat n as an unsigned value
    public static int hammingWeight(int n) {
       if(n==0) return 0;
       if(n==1) return 1;
       int total=1;
       int index=1;
       while(n-total*2>=0){
           total=total*2;
       }
       n=n-total;
       index=index+hammingWeight(n);
       return index;
  }


2.用位运算方法

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
     if(n==0) return 0;
     int i=0;
     while(n!=0){
         n=n & (n-1);
         i++;
     }
     return i;
  }
}




/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/


目录
相关文章
|
3月前
|
存储 算法 程序员
【Leetcode 程序员面试金典 01.01】判定字符是否唯一 —— 位运算|哈希表
可以使用哈希表或位运算来解决此问题:由题可知s[i]仅包含小写字母,int[26]即能表示字符的出现次数;
|
3月前
|
Java 程序员
【Leetcode 程序员面试金典 05.01】插入 —— 位运算
位运算问题,只需要把 N 的 i 到 j 位都置 0 后再和 M 左移 i 位的结果进行按位或即可
|
5月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
63 1
|
5月前
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
21 0
|
8月前
|
算法 C语言 C++
【位运算问题】Leetcode 136、137、260问题详解及代码实现
此外,任意一个数异或0都为他本身 (这从二进制编码来理解也很好理解,0的二进制编码全为0,任意一个数与其异或不同的就是若干位的1)
51 0
|
算法
leetcode-每日一题1217. 玩筹码(贪心+位运算)
判断元素的奇偶性,把奇数下标记录在odd 元素里
57 0
leetcode-每日一题1217. 玩筹码(贪心+位运算)
|
缓存 Java 程序员
|
Java Linux
LINUX编译OPENJDK:The tested number of bits in the target (0) differs from the number of bits expected
LINUX编译OPENJDK:The tested number of bits in the target (0) differs from the number of bits expected
143 0
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number