当前位置:网站首页>剑指Offer | 二进制中1的个数
剑指Offer | 二进制中1的个数
2022-07-25 14:59:00 【小雅痞】
输入一个整数 n ,输出该数32位二进制表示中1的个数。其中负数用补码表示。
方法1:
方法1: 将32位每一位都与1相与。统计1的个数。
public int NumberOf1(int n) {
int cnt = 0;
//方法1: 将32位每一位都与1相与。统计1的个数。
// 1的32进制: 0000...1 1<<i:通过逐渐左移,使得1能够与n的每一位相与
for(int i=0;i<32;i++){
if((n & (1<<i)) != 0){
cnt++;
}
}
return cnt;
}
方法2:
方法2: 逐渐将n右侧的1变为0.
public int twoNumberOf1(int n) {
int cnt = 0;
// 方法2: 逐渐将n右侧的1变为0.
// n = n & (n-1); 将n最右侧的1变为0
while (n != 0){
cnt ++;
n = n & (n-1);
}
return cnt;
}
方法3:
方法3:将数字n转化为32位字符串的形式。
public int threeNumberOf1(int n) {
int cnt = 0;
// 方法3:将数字n转化为32位字符串的形式。
String numStr = Integer.toBinaryString(n);
for(int i=0;i<numStr.length();i++){
if(numStr.charAt(i)=='1'){
cnt++;
}
}
return cnt;
}
边栏推荐
- 39 simple version of millet sidebar exercise
- Deng Qinglin, a technical expert of Alibaba cloud: Best Practices for disaster recovery and remote multi activity across availability zones on cloud
- Several methods of spark parameter configuration
- (原创)自定义一个滚屏的RecyclerView
- 45padding不会撑开盒子的情况
- "Ask every day" reentrantlock locks and unlocks
- 直播课堂系统05-后台管理系统
- QT connect, signal, slot and lambda comparison
- MFC 线程AfxBeginThread基本用法,传多个参数
- Qt connect 中, SIGNAL,SLOT 与 lambda 对比
猜你喜欢

瀑布流布局

"Ask every day" briefly talk about JMM / talk about your understanding of JMM

27 选择器的分类

Visual Studio 2022 查看类关系图

L1和L2正则化

SQL优化的一些建议,希望可以帮到和我一样被SQL折磨的你

Gonzalez Digital Image Processing Chapter 1 Introduction

Heyuan City launched fire safety themed milk tea to boost fire prevention and control in summer

ESXI6.7.0 升级到7.0U3f(2022年7月12 更新)

【微信小程序】小程序宿主环境详解
随机推荐
Fast-lio: fast and robust laser inertial odometer based on tightly coupled IEKF
006 operator introduction
LeetCode_因式分解_简单_263.丑数
I2C设备驱动程序的层次结构
(原创)自定义一个滚屏的RecyclerView
Implementation of redis distributed lock
CMake指定OpenCV版本
Implement a simple restful API server
【JS高级】js之正则相关函数以及正则对象_02
Awk from entry to earth (24) extract the IP of the instruction network card
Leo-sam: tightly coupled laser inertial odometer with smoothing and mapping
Process control (Part 1)
BigDecimal rounds the data
ice 100G 网卡分片报文 hash 问题
Stored procedure bias of SQL to LINQ
关于RDBMS和非RDBMS【数据库系统】
"Ask every day" briefly talk about JMM / talk about your understanding of JMM
Bridge NF call ip6tables is an unknown key exception handling
Raft of distributed consistency protocol
37 元素模式(行内元素,块元素,行内块元素)