LeetCode 191. Number of 1 bits (位1的数量)
2024-10-19 14:33:06
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
最新文章
- ssh 的搭建
- 提示框alertmsg
- HDU 5127 Dogs&#39; Candies
- Factorial Solved Problem code: FCTRL
- php给数组key:value中的key加引号
- 一款基于Vue的扩展性组件库 VV-UI
- UNIX DOMAIN SOCKET效率
- MySQL数据库聚合函数
- php Header 函数使用
- CLR查找和加载程序集的方式(一)
- 建立uboot,内核的SI工程(1)
- PHP跳出循环的方法及continue、break、exit的区别
- 乘风破浪:LeetCode真题_038_Count and Say
- npm 安装文件 运行报错 %1 is not a valid Win32 application
- 手动设置3G的wifi迷你无线路由
- 20155236 2016-2017-2 《Java程序设计》第五周学习总结
- Ubuntu tar方式安装mysql5.7.21 时报错 [ERROR] Can&#39;t locate the language directory. 以及 ------ libaio.so.1: cannot open shared object file
- 深入浅出python系列(一)包与模块
- Django学习笔记(一):环境安装与简单实例
- npm无法安装全局web3的问题
热门文章
- Vue跨门槛系列之实例的阐述
- JavaScript基础回顾
- webservice06#异常#Handler
- Laravel的Nginx重写规则完整代码
- [UIKit学习]08.关于自定义控件
- Spring+SpringMVC+MyBatis整合进阶篇(四)RESTful实战(前端代码修改)
- 安装Vue2的devtools发生错误npm ERR! code EINTEGRITY npm ERR! sha1-HTFDXrRzR2Ew8Bv9zlMSCVgPsS0= integrity checksum failed when using sha1: wanted sha1-HTFDXrRzR2Ew8Bv9zlMSCVgPsS0= but got sha1-Z6BeTMF4nhAO6h5A
- Java钉钉开发_02_免登授权(身份验证)(附源码)
- Hive简记
- Codeforces Round #430 (Div. 2)