当前位置:网站首页>【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;
}
}
边栏推荐
- 7.27 minimum spanning tree phased test problem solution
- 今天和大家聊一聊mysql数据库的数据类型
- 极致通缩和永动机模型,将推动 PlatoFarm 爆发
- How to learn so many conceptual things in database? Seeking method
- 2022-7-27周报
- PHP connection MySQL native code
- 路由器固件解密思路
- MySQL master-slave architecture. After the master database is suspended and restarted, how can the slave database automatically connect to the master database
- 能够遍历一个文件夹下的所有文件和子文件夹
- The high temperature continues, and public transport enterprises carry out special safety training
猜你喜欢

Pulse style | exclusive interview with Committee -- Tencent engineer Zhang Dawei calls you to eat "crab"

深度学习必懂的 13 种概率分布

2022-7-27周报

Boss: there are too many systems in the company. Can we realize account interworking?

Read Plato farm's eplato and the reason for its high premium

OpenAtom OpenHarmony分论坛,今天14:00见!附大事记精彩发布

Create SSL certificate using OpenSSL
![[OpenHarmony] [RK2206] 构建OpenHarmony编译器 (二)](/img/0c/2e8290403d64ec43d192969f776724.png)
[OpenHarmony] [RK2206] 构建OpenHarmony编译器 (二)

Basic examples that must be mastered by beginners of C #

C# 读写文件从用户态切到内核态,到底是个什么流程?
随机推荐
备受关注的Bit.Store,最新动态一览
Basic knowledge of redis
Edge团队详解如何通过磁盘缓存压缩技术提升综合性能体验
SizeBasedTriggeringPolicy简介说明
OSS direct upload rails service practice
博弈论 1.Introduction(组合游戏基本概念、对抗搜索、Bash游戏、Nim游戏)
如何使用JWT进行身份验证与授权
Seektiger eco pass STI new progress, log in to ZB on April 14
PHP连接mysql原生代码
Introduction to consoleappender
Mock.js
In php7?? And?: Differences between
PHP connection MySQL native code
Experiment 5: user and user group management
数据不会说谎,Plato Farm就是元宇宙龙头
建筑建材行业B2B电子商务网站方案:赋能建材企业转型升级,实现降本提效
Installing MySQL for Linux operating system (centos7)
fastjson中@jsonType注解的功能简介说明
OSPF的拓展配置,选路原则,防环及重发布
FixedWindowRollingPolicy简介说明