当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
仿牛客网项目第二章:开发社区登录模块(详细步骤和思路)
How to run dist file on local computer
【愚公系列】2022年07月 Go教学课程 021-Go容器之切片操作
ACL 2022 | Introduce angular margin to construct comparative learning objectives and enhance text semantic discrimination ability
Apache DolphinScheduler's new generation of distributed workflow task scheduling platform in practice - Part 1
新手必备!最全电路基础知识讲解
MySQL【运算符】
嘉为鲸翼·多云管理平台荣获信通院可信云技术服务最佳实践
Kotlin 值类 - value class
电路分析:运放和三极管组成的恒流源电路
随机推荐
日志导致线程Block的这些坑,你不得不防
R安装包出现error in rawtochar(block[seq_len(ns)]) :
2022杭电多校第二场
2022 Hangzhou Electric Multi-School 1st Game
The sword refers to offer 48: the longest non-repeating substring
【零基础玩转BLDC系列】以GD32F30x为例定时器相关功能详解
积分专题笔记-与路径无关条件
ACL 2022 | Introduce angular margin to construct comparative learning objectives and enhance text semantic discrimination ability
Circuit analysis: constant current source circuit composed of op amp and triode
Oracle 创建和操作表
Golang DES 加解密如何实现?
Unity performance analysis Unity Profile performance analysis tool
0729放假自习
一个低级错误导致的诡异现象——走近科学能拍三集,(C语言)最简单的数组元素读取,不正确!?
Use the R language to read the csv file into a data frame, and then view the properties of each column.
回板后,处理器不启动,怎么办?
【HMS core】【FAQ】HMS Toolkit典型问题合集1
统一异常处理导致ResponseBodyAdvice失效
Kotlin value class - value class
Leetcode - 990: equations of satisfiability