10.2lc
刷了一下午的 位运算… 共有13道题…
脑袋秃了…
吐槽一哈: 真的 有的位运算 方法 真的有人能想出来?? 反正我是毫无头绪 ,全部暴力来做的… 太菜了
不过 写位运算 可以帮助我们 理解计算机的运算过程。(ps: 反正都是 API调用师…)
位运算的基本概念
- 原码
- 反码
- 补码
- 有符号数
- 无符号数
- 左移 右移 1<< >>1
- 异或: 这是个 好东西 简单记忆: 1^0 =1;
405. 数字转换为十六进制数 - 力扣(LeetCode) (leetcode-cn.com)
:没啥算法 就是个 sb 进行并接 每四位 进行 & 预算
class Solution {
public String toHex(int num) {
if (num == 0) return "0";
char[] map = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBuilder sb = new StringBuilder();
while (num != 0) {
// 并接子父 和 15 取余
sb.append(map[num & 0b1111]);
// 往后移 4 位
num >>>= 4;
}
return sb.reverse().toString();
}
}
191. 位1的个数 - 力扣(LeetCode) (leetcode-cn.com)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res=0;
while( n != 0){
//将后面的 1 反转为 0 往后走
n=n&(n-1);
res++;
}
return res;
}
}
461. 汉明距离 - 力扣(LeetCode) (leetcode-cn.com)
:上面的思路差多: 将两个数先 异或成一个数 再和上体一样就可
class Solution {
public int hammingDistance(int x, int y) {
int n=x^y,res=0;
while(n != 0){
n=n&(n-1);
res++;
}
return res;
}
}
29. 两数相除 - 力扣(LeetCode) (leetcode-cn.com)
:要求不让用除法 可以用减法~~~~ 除法的本质 :就是减法 :
但是 如果 直接迭代 超时… 所以成倍的迭代即可
class Solution {
public int divide(int dividend, int divisor) {
//超时
if(dividend == 1<< 31 && divisor == -1 ) return (1<<31)-1;
//判断 符号 异或 不同 为 true;
int sing = (dividend > 0) ^ (divisor >0) ? -1: 1;
//取正
long a=Math.abs((long)dividend);
long b =Math.abs((long)divisor);
int res =0;
int i=0;
//每次相减 就可 例子: 6/3 ==> 6-3-3
while( a-b >=0){
long temp =b;
int m=1;
while(temp << 1 <= a){
//成倍 区间 每次 2的次方
temp <<=1;
m<<= 1;
}
a=a-temp;
res+=m;
}
return res * sing;
}
}
201. 数字范围按位与 - 力扣(LeetCode) (leetcode-cn.com)
思路找到公共前缀后 后面加0
class Solution {
public int rangeBitwiseAnd(int left, int right) {
int a=0;
while( left != right){
left >>=1;
right>>=1;
a++;
}
return left<<a;
}
}