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.


题目标签:Bit Manipulation

  这题给我们一个integer,让我们找到bits中1的个数,利用 & 1 判断bit是不是1,然后利用 >> 来移动bits。

Java Solution:

Runtime beats 16.07%

完成日期:06/26/2017

关键词:Bit Manipulation

关键点:用 & 拿到bit, 用 >> 来移动bits

 public class Solution
{
// you need to treat n as an unsigned value
public int hammingWeight(int n)
{
int res = 0; for(int i=0; i<32; i++)
{
if((n & 1) == 1) // meaning the most right bit is 1
res++; n = n >> 1; // shift to right 1 bit
} return res;
}
}

参考资料: N/A

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

最新文章

  1. ssh 的搭建
  2. 提示框alertmsg
  3. HDU 5127 Dogs&#39; Candies
  4. Factorial Solved Problem code: FCTRL
  5. php给数组key:value中的key加引号
  6. 一款基于Vue的扩展性组件库 VV-UI
  7. UNIX DOMAIN SOCKET效率
  8. MySQL数据库聚合函数
  9. php Header 函数使用
  10. CLR查找和加载程序集的方式(一)
  11. 建立uboot,内核的SI工程(1)
  12. PHP跳出循环的方法及continue、break、exit的区别
  13. 乘风破浪:LeetCode真题_038_Count and Say
  14. npm 安装文件 运行报错 %1 is not a valid Win32 application
  15. 手动设置3G的wifi迷你无线路由
  16. 20155236 2016-2017-2 《Java程序设计》第五周学习总结
  17. Ubuntu tar方式安装mysql5.7.21 时报错 [ERROR] Can&#39;t locate the language directory. 以及 ------ libaio.so.1: cannot open shared object file
  18. 深入浅出python系列(一)包与模块
  19. Django学习笔记(一):环境安装与简单实例
  20. npm无法安装全局web3的问题

热门文章

  1. Vue跨门槛系列之实例的阐述
  2. JavaScript基础回顾
  3. webservice06#异常#Handler
  4. Laravel的Nginx重写规则完整代码
  5. [UIKit学习]08.关于自定义控件
  6. Spring+SpringMVC+MyBatis整合进阶篇(四)RESTful实战(前端代码修改)
  7. 安装Vue2的devtools发生错误npm ERR! code EINTEGRITY npm ERR! sha1-HTFDXrRzR2Ew8Bv9zlMSCVgPsS0= integrity checksum failed when using sha1: wanted sha1-HTFDXrRzR2Ew8Bv9zlMSCVgPsS0= but got sha1-Z6BeTMF4nhAO6h5A
  8. Java钉钉开发_02_免登授权(身份验证)(附源码)
  9. Hive简记
  10. Codeforces Round #430 (Div. 2)