当前位置:网站首页>【JZOF】15二进制中1的位数
【JZOF】15二进制中1的位数
2022-07-28 09:44:00 【叹了口丶气】
题目描述:
输入一个整数 n ,输出该数32位二进制表示中1的个数。其中负数用补码表示。
直接遍历去做:
public class Solution {
public int NumberOf1(int n) {
int res = 0;
//遍历32位
for(int i = 0; i < 32; i++){
//按位比较
if((n & (1 << i)) != 0)
res++;
}
return res;
}
}
小特性:n & (n-1)会让最后一位的1变成0.
public class Solution {
public int NumberOf1(int n) {
int res = 0;
//当n为0时停止比较
while(n != 0){
n &= n - 1;
res++;
}
return res;
}
}
边栏推荐
- Include and require include_ Once and require_ Once difference
- SizeBasedTriggeringPolicy简介说明
- Bit.store, which has attracted much attention, is at a glance of the latest developments
- Introduction to consoleappender
- Sequence and limit operation of MATLAB
- 总线相关概念集合
- TCP 基础知识
- NTU Lin Xuantian's "machine learning cornerstone" problem solving and code implementation | [you deserve it]
- (iros 2022) monocular visual inertial odometer based on event camera
- Seeing clearly is more important than walking fast, because you can go far only when you walk right
猜你喜欢
![[ESP32][esp-idf][LVGL7.9] 使用oled iic编译失败](/img/16/e5aa43df6ef9bdbc173fa547c85559.png)
[ESP32][esp-idf][LVGL7.9] 使用oled iic编译失败

Real time editor of MATLAB

超级原始人系列盲盒即将上线,PlatoFarm赋能超多权益

Weekly report on July 27, 2022

C countdown tool
JWT 登录认证 + Token 自动续期方案,写得太好了!

Standing on the shoulders of big men, you can see further

在Plato Farm新经济模型下,如何在游戏中获取更多MARK

居家健康诊断时代下,Senzo打造增强侧向流测试产品

Have you ever seen this kind of dynamic programming -- the stock problem of state machine dynamic programming (Part 2)
随机推荐
ASP.NET Core 6框架揭秘实例演示[29]:搭建文件服务器
PHP Basics
The high temperature continues, and public transport enterprises carry out special safety training
PHP 常用的数组整理
【MySQL】查询多个ID返回字符串拼接
Several innovative economic models of platofarm have inspired the current metacosmic market
NET 3行代码实现文字转语音功能
关于CLR GC调优的一些问题
fastjson中@jsonType注解的功能简介说明
Experiment 4 uses fdisk to manage hard disk
Sequence and limit operation of MATLAB
Mock.js
Linux操作系统(Centos7)安装MySQL
(十)defer关键字
对象到对象映射-AutoMapper
Introduction to thresholdfilter
Branches and loops (1)
In hot weather, the line of defense for safe production was strengthened, and Guangzhou Haizhu District carried out emergency drills for gas stations
EvaluatorFilter简介说明
Array method of J S, loop