C#LeetCode刷题之#191-位1的个数(Number of 1 Bits)
问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4052 访问。
编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
输入: 11
输出: 3
解释: 整数 11 的二进制表示为 00000000000000000000000000001011
输入: 128
输出: 1
解释: 整数 128 的二进制表示为 00000000000000000000000010000000
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011
Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000
示例
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4052 访问。
public class Program {
public static void Main(string[] args) {
var n = 11U;
var res = HammingWeight(n);
Console.WriteLine(res);
n = 128U;
res = HammingWeight2(n);
Console.WriteLine(res);
Console.ReadKey();
}
public static int HammingWeight(uint n) {
//10进制转2进制,除2取余法
var count = 0;
while(n != 0) {
if(n % 2 != 0) count++;
n /= 2;
}
return count;
}
public static int HammingWeight2(uint n) {
//基本思路同 HammingWeight
var count = 0;
while(n != 0) {
//10进制的1,2,3,4,5对应于2进制的1,10,11,100,101
//由于2进制的特点,末位数在1,0之间循环
//用 n 和 1 做“与运算”若值为1,必为奇数
//即除2余1
if((n & 1) == 1) count++;
//2进制右移1位即10进制除2
n >>= 1;
}
return count;
}
}
以上给出2种算法实现,以下是这个案例的输出结果:
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4052 访问。
3
1
分析:
显而易见,以上2种算法的时间复杂度均为: 。
最新文章
- Windows中遇到的些问题及解决办法
- innerHTML、innerText、outerHTML、outerText的区别
- luemn PHP_CodeSniffer的安装
- Oracle备份 还原命令
- ASP.NET Web API 2 中的特性路由
- AppInventor学习笔记(五)——瓢虫快跑应用学习
- Data URL
- ios 7 20像素解决
- 【转】为什么我说 Android 很糟糕
- syntax error: missing ';' before identifier 'IWebBrowser'
- pl_sql 报ora-12154 无法解析指定的连接标识符的问题
- IOS 物理引擎
- 11181 - Probability|Given
- Wix学习整理(1)——快速入门HelloWorld
- jquery easyui datagrid改变某行的值
- SSH(struts2+hibernate+spring)总结
- 基本服务器的AAA实验(Cisco PT)
- jenkins命令行修改时间
- 项目代码迁移(使用git)
- box-sizing的用法
热门文章
- 盘点JMeter不为人知那一些细节
- Python Ethical Hacking - MAC Address &; How to Change(1)
- Python Ethical Hacking - BACKDOORS(1)
- pyinstall打包资源文件
- POJ2774 --后缀树解法
- Ribbon负载均衡接口
- Image Processing Using Multi-Code GAN Prior, CVPR2020
- 今天成功完成二维码扫描程序, 利用zxing
- python关于字符编码的基本操作
- LQB2013A05前缀判断