LeetCode 191 Number of 1 Bits
LeetCode 191 Number of 1 Bits
解法一(较为传统都解法):使用将n不断右移,并与1想&得到1的个数;(也有使用除法/2的,明显除法的运行效率要低于位移)
时间复杂度:0(logn)
1 int hammingWeight(uint32_t n){ 2 int count=0; 3 4 while (n!=0) { 5 if (n & 1) { 6 ++count; 7 } 8 n = n>>1; 9 } 10 11 return count; 12 }
解法二:
使用n&(n-1)的方法
假使 n =0x110101
n n-1 n&(n-1)
step1: 110101 110100 110100
step2: 110100 110011 110000
step3: 110000 101111 100000
step4: 100000 011111 000000
发现有几个1,就循环几次n&(n-1)得到0,明显较于上者运行效率更高些。
时间复杂度:O(M),M是n中1的个数。
代码如下:
1 int hammingWeight(uint32_t n){ 2 int count=0; 3 4 while (n!=0) { 5 count++; 6 n = n&(n-1); 7 } 8 9 return count; 10 }
转载于:https://www.cnblogs.com/wudongyang/p/4337295.html
LeetCode 191 Number of 1 Bits相关推荐
- [勇者闯LeetCode] 191. Number of 1 Bits
[勇者闯LeetCode] 191. Number of 1 Bits Description Write a function that takes an unsigned integer and ...
- leetcode 191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also know ...
- LeetCode - Easy - 191. Number of 1 Bits
Topic Bit Manipulation Description https://leetcode.com/problems/number-of-1-bits/ Write a function ...
- leetcode python3 简单题191. Number of 1 Bits
1.编辑器 我使用的是win10+vscode+leetcode+python3 环境配置参见我的博客: 链接 2.第一百九十一题 (1)题目 英文: Write a function that ta ...
- 【LeetCode从零单排】No 191.Number of 1 Bits(考察位运算)
题目 Write a function that takes an unsigned integer and returns the number of '1' bits it has (also k ...
- 【LeetCode】191. Number of 1 Bits
题目: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also ...
- Leet Code OJ 191. Number of 1 Bits [Difficulty: Easy]
题目: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also ...
- 【Leetcode】Number of 1 Bits(easy)
Question Write a function that takes an unsigned integer and returns the number of '1' bits it has ( ...
- 191. Number of 1 Bits
最新文章
- 排查 Node.js 服务内存泄漏,没想到竟是它?
- java基于udp实现键盘录入聊天
- pythoncsv格式列变换_用Python将csv行转换为列
- 【Elasticsearch】Nori:官方的韩语分析插件Elasticsearch
- require include php5中最新区别,百度上好多错的。
- 原生 js 轮播图(8)
- 蓝桥杯2015年第六届C/C++省赛A组第九题-垒骰子
- 【Stanford Online】Engineering: Algorithms1 NO.4 The Master Method
- 什么计算机有hdmi接口,hdmi接口是什么?hdmi是什么?
- 读后感之悟道-一位20年IT高管的职场心得
- c语言数组统计选票,C语言实现选票统计
- excel数组公式中的意想不到的坑
- WebRTC VideoEngine综合应用示例(一)——视频通话的基本流程
- 触摸中国人工智能最前线
- Linux上:使用VMware17安装Centos8.5并配置网络、WSL安装Ubuntu、
- 多数据库应用加强,增加表枚举约定数据库链接配置
- 计算机在生物工程的应用,计算机在化学化工及生物工程中的应用
- 面试官:Redis如何实现持久化的、主从哨兵又是什么?
- LocalDB 声称以后对于中文乱码的问题
- 闲鱼客服工具/消息管理系统:可以让客服放下手机,在电脑上管理闲鱼店铺的咨询信息
热门文章
- inside java security_Inside The JVM Part2: java如何实现安全性
- 3d stroke插件下载_推荐一款好用的PS 3D地图插件,PS插件3D Map Generator ,一键生成地图神器...
- java基础线程_Java基础之多线程没那么复杂!
- step如何打开服务器项目,STEP7项目打开及删除
- java事件处理模型_从零开始理解JAVA事件处理机制(3)
- 反arp攻击软件_谈谈电子欺骗中的ARP欺骗
- python pip指令_python 常用 pip 命令合集
- mysql 事务隔离规范_MySQL事务隔离级别以及脏读、幻读、不可重复读示例
- 基于近距离的测距感知传感器调研以及扩展介绍
- C++:随笔9----模板/内联函数/容器