[LintCode] Count 1 in Binary
2015-08-15 09:57
423 查看
Count how many
Example
Given
Given
Given
Challenge
If the integer is n bits with m 1 bits. Can you do it in O(m) time?
常规解法:
使用STL的解法:
1in binary representation of a 32-bit integer.
Example
Given
32, return
1
Given
5, return
2
Given
1023, return
9
Challenge
If the integer is n bits with m 1 bits. Can you do it in O(m) time?
常规解法:
class Solution { public: /** * @param num: an integer * @return: an integer, the number of ones in num */ int countOnes(int num) { // write your code here int cnt = 0; while(num != 0){ cnt += (num&1); num >>= 1; } return cnt; } };
使用STL的解法:
#include <bitset> class Solution{ public: /** * @param num: an integer * @return: an integer, the number of ones in num */ int countOnes(int num) { // write your code here bitset<sizeof(int)*8> bitvec(num); return bitvec.count(); } };
相关文章推荐
- 手动编译安装nginx
- iOS 代理为啥要用weak修饰? (刨根问底一)
- 字典树模板
- 霓歌即时通讯中的相关专利整理(七)
- jQuery实现图片渐入渐出切换展示效果
- PowerPoint巧妙确定圆心的技巧商务ppt模板
- python快速使用(三)类、异常
- java.lang.Class Cast Exception: android.widget.HeaderViewListAdapter
- 配置java环境变量
- eclipse在线安装插件
- Android的TextView/EditText使用CharacterStyle&SpannableString来处理图片显示、字体样式、超链接等
- iOS 万能跳转界面方法(runtime实用篇一)
- AngularJs学习笔记__5、内置过滤器
- 针对初学者的jQuery入门指南
- NFS服务详细分析
- 用pdo实现的织梦后台留言板
- C语言宏定义和宏定义函数
- java线程池的基本使用
- Python Version 2.7 required which was not found in the registry 问题解决
- (大数据工程师学习路径)第四步 SQL基础课程----创建数据库并插入数据