当前位置:网站首页>leetcode 剑指 Offer 15. 二进制中1的个数
leetcode 剑指 Offer 15. 二进制中1的个数
2022-07-30 08:52:00 【kt1776133839】
题目描述:
编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为 汉明重量).)。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用 二进制补码 记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。
样例:
示例 1:
输入:n = 11 (控制台输入 00000000000000000000000000001011)
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:
输入:n = 128 (控制台输入 00000000000000000000000010000000)
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:
输入:n = 4294967293 (控制台输入 11111111111111111111111111111101,部分语言中 n = -3)
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
提示:
输入必须是长度为 32 的 二进制串 。
解题思路:
巧用 n&(n−1)
(n−1)解析: 二进制数字 n 最右边的 1 变成 0 ,此 1 右边的 0 都变成 1 。
n&(n−1) 解析: 二进制数字 n 最右边的 1 变成 0 ,其余不变。

算法流程:
初始化数量统计变量 res 。
循环消去最右边的 1 :当 n=0时跳出。
res += 1 : 统计变量加 1 ;
n &= n - 1 : 消去数字 n 最右边的 1 。
返回统计数量 res 。
Java程序:
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res++;
n &= n - 1;
}
return res;
}
}
边栏推荐
- Activating data potential Amazon cloud technology reshapes cloud storage "family bucket"
- conda 导出/导出配置好的虚拟环境
- Unity performance analysis Unity Profile performance analysis tool
- 激活数据潜力 亚马逊云科技重塑云上存储“全家桶”
- 使用 Neuron 接入 Modbus TCP 及 Modbus RTU 协议设备
- 研发转至FAE(现场应用工程师),是否远离技术了?有前途吗?
- 如何组装一个注册中心
- Liunx服务器安装SVN(安装包版)
- The difference between DDR, GDDR, QDR
- 七大排序之直接选择排序
猜你喜欢

How to run dist file on local computer

Concise Notes on Integrals - Types of Curve Integrals of the Second Kind

Apache DolphinScheduler's new generation of distributed workflow task scheduling platform in practice - Part 1

Google Cloud Spanner的实践经验

XP电源维修fleXPower电源X7-2J2J2P-120018系列详解

【 HMS core 】 【 】 the FAQ HMS Toolkit collection of typical questions 1

用示波器揭示以太网传输机制

Integral Special Notes-Three Formulas for Curve Area Integral

HCIP --- MPLS VPN实验

Two solutions for Excel xlsx file not supported
随机推荐
Unable to locate the program input point ucrtbase.abort on the dynamic link library api-ms-win-crt-runtime-|1-1-0.dll
硬件工程师
ClickHouse
企业数字化建设,自研还是采购?
20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
【无标题】
Jenkins 如何玩转接口自动化测试?
2022 Hangzhou Electric Multi-School 1st Game
conda 导出/导出配置好的虚拟环境
日志导致线程Block的这些坑,你不得不防
【HMS core】【FAQ】HMS Toolkit典型问题合集1
开关电源波纹的产生、测量及抑制,一篇全搞定!
MySQL [operator]
实施敏捷过程中这些常见的问题你可曾遇到?
公共Jar包的版本管理
电源完整性基础知识
Excel xlsx file not supported两种解决办法【杭州多测师】【杭州多测师_王sir】
Concise Notes on Integrals - Types of Curve Integrals of the First Kind
PyTorch安装及环境配置(Win10)
微软 SQL 服务器被黑,带宽遭到破坏