Counting Bits leetcode 338
来源:互联网 发布:产品报价系统源码 编辑:程序博客网 时间:2024/05/16 10:05
题目大意:计算数字的二进制中'1'的个数。
思路:计算'1'的个数是常见的题目了,什么 x&x-1 把最右边的1变成0 ,什么 y | y+1把最右边的0变成1之类的,常见不鲜。
根据题后面的hints,计算较大的数时可以利用前面的计算结果,把同余数位置上已经得到的结果+1就行,比如计算7的结果,只要用3的结果+1即可。carry的值要根据计算到的值,每到2的幂就左移1位。
AC code:
class Solution {public: vector<int> countBits(int num) { vector<int> res(num + 1); for (int i = 1, carry = 0; i <= num; ++i) { if (i & i - 1) { res[i] = res[i - carry] + 1; } else { res[i] = 1; if(carry > 0) carry <<= 1; else ++carry; } } return res; }};
0 0
- leetcode:bits:Counting Bits(338)
- 【LeetCode-338】Counting Bits
- leetcode-338-Counting Bits
- Leetcode 338 Counting Bits
- LeetCode 338 :Counting Bits
- [leetcode-338]Counting Bits
- 【LeetCode-338】 Counting Bits
- LeetCode 338 Counting Bits
- Counting Bits leetcode 338
- [LeetCode 338] Counting Bits
- LeetCode-338:Counting Bits
- LeetCode-338:Counting Bits
- LeetCode[338] Counting Bits
- LeetCode#338 Counting Bits
- LeetCode 338 Counting Bits
- LeetCode 338 Counting Bits
- Leetcode #338 Counting Bits
- Leetcode 338 Counting Bits
- 3.1.1 什么是Memcached
- linux安装
- ELK实战-Logstash:收集rsyslog日志
- Dubbo架构设计详解
- FZU 2135---数字游戏
- Counting Bits leetcode 338
- android layout_weight 使用总结
- RxJava学习笔记
- throw和throws是的区别
- ELK实战-Logstash multiline:识别错误堆栈
- 习题7-2 UVA - 225 Golygons (简单的暴力回溯法+剪枝)
- 关于android studio中装插件genymotion时遇到的一些问题
- XML解析(SAX解析和DOM解析)
- linux用shell发邮件