一、十进制 转 二进制
f1 利用:num.toString(2)转二进制
f2 利用栈:
循环至n为0:n对2的余数入栈;n除2,取整;
依次出栈;
function toB (num) {
let res = ''
const stack = new Stack();
while (num) {
stack.push(num % 2)
num = parseInt(num / 2)
}
while (stack.length()) {
res += stack.pop()
}
return res
}
二、按位运算
let n=10;
-
n>>1 , 右移1位,除2
-
n<<1 , 左移1位,乘2
-
n=n^(n-1) 将最后1个1转为0
如,LeetCode 191. 位1的个数- 法1:toString + for遍历数1,时间:遍历s,O(n);空间:字符串的长,O(n);
- 法2:利用位的性质
let res=0; while(n){ n&=n-1; res++; } return res;