58同城题目
58同城出了三道算法题,第一道题题目过长。。。好像是和推荐系统挂钩的题目(给CV一条活路吧!T T)
第二道题还有第三道题都是leetcode上很简单的题目(第一次2AC!主要还是题目简单)
主要想说一下第二道题目,
给定一个非负整数num,求在0<=x<=num区间中的所有整数的二进制数中1的个数,空间复杂度为O(n)。
如:
输入:
3
输出:
[0,1,1,2]
输入:
5
输出:
[0,1,1,2,1,2]
题解:
这道题看起来不难,我们可以观察到如果x是2的指数倍的话,x的二进制中的1的个数就是1,但是要求空间复杂度为O(n),所以我们不能用递归的方法去判断当前的数字是否是2的指数。
所以引入如果x是2的指数,那么
x & (x-1) == 0
的规律
且还有如果x不是2的指数,那么
x & (x-1) == x-1
的规律
在这里说一下&的用法,这是个二进制运算符,会将运算数转换成二进制进行运算
1 & 1 = 1, 1 & 0 = 0, 0 & 1 = 0, 0 & 0 = 0;
另外,除了&之外,还有 | 运算符和 ~ 运算符。
1 | 1 = 1, 1 | 0 = 1, 0 | 1 = 1, 0 | 0 = 0;
~0 = 1, ~1 = 0;
所以程序为:
public class problem1 {
public static void main(String[] args) {
demo1 d1 = new demo1();
int[] results = d1.countBits(5);
for (int i:results){
System.out.println(i);
}
}
}
class demo1{
public int[] countBits (int num) {
// write code here
int[] res = new int[num+1];
res[0] = 0;
for (int i = 1;i <= num;i++){
res[i] = numc(i);
}
return res;
}
public int numc(int i){
int count = 0;
while (i != 0){
count += 1;
i = (i-1)&i;
}
return count;
}
}