LeetCode 338. Counting Bits
来源:互联网 发布:阿里云视频点播 编辑:程序博客网 时间:2024/06/03 18:11
今天开始,刷leetcode!一方面重新熟练编程,一方面为面试做准备!
同时,记录每道题,并且要解释清楚,为的是面试能解释给面试官听!
题意:求出【0,1,2,3……num】他们每个数字的二进制的1的个数
思路:
用举例法
8的二进制是1000, 15的二进制是1111
即8~15的二进制是1000~1111
第一位永远是1
则其countbit数量取决于000~111这个过程
而000~111也就是0~7,在之前已经计算过了,即可以直接利用
即8~15的countbit为p[i]=p[i-8],edg为8,即差值
同理,16~31就是10000到11111,而0000~1111的countbit数量前面已经知道了
所以16~31的countbit为p[i]=p[i-16],差值edg为16
所以照着这个思路很快就能写出答案,重要的是如何求edg
C\C++:
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* countBits(int num, int* returnSize) { int i=0;int edg=1;int *ans,*p;p=malloc((num+1)*sizeof(int)); //分配内存,num+1个而不是num个*returnSize=num+1; //返回总个数ans=p; //ans指向数组首地址,p用来计算*p=0; //第一个是0p++;i=1;while(i<=num){*p=1+*(p-edg); //由之前所计算的得到答案i++;p++;if(i==edg*2) //当i等于差值*2时,改变差值edg=edg*2;}return ans;}
python:
class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ ans=[0] edg=1; i=1; while i<=num: ans.append(1+ans[i-edg]) i+=1 if i==edg*2: edg=edg*2 return ans
1.C++中,对len长的int数组的new的形式为p=new int[len]
2.C中,为malloc(num*sizeof(int))
3.注意观察题意,returnSize顾名思义就是长度,函数返回值为一个指针,那么肯定就是所求数组。
4.python中,列表就像数组,往数组尾端加元素只需要用append函数即可!
0 0
- [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
- (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
- Java IO ByteArrayInputStream和ByteArrayOutputStream
- Codeforces Round #332 (Div. 2)C. Day at the Beach
- Oracle数据库的学习(一)
- java中的分布式应用(一)之分布式介绍
- Java实现快速排序(泛型)
- LeetCode 338. Counting Bits
- Ubuntu服务器的NVIDIA驱动自动更新所引起的问题及解决方法m
- 笔记--ThinkPHP运行流程
- 正则表达式
- 判断当前rom为MIUI或Flyme或android m
- Android Studio 主题、字体大小的设置
- 《Windows核心编程》之“线程调度和优先级”
- 后缀数组
- bios x86保护模式下的软盘操作floppy