前言:位移运算就是二进制,位移进行左移或右移操作,其不需要转换成十进制,处理速度很快,位移运算符在算法方面也有应用,力扣上找了几道题练习位运算。
目录
思维导图:
力扣191
数二进制位有多少个1
思路:
1、 从右边第一位开始,用n&1计算,结果为1,count+1;判断完右边第一位后,往右移一位,再以同样的方法去判断从右边起第二位
时间复杂度O(1),需要检查32次
2、n&n-1,将n最后一位的1清除,(1000&0111=0,11000&10111=10000)
每次与的结果不为0,就一直进行下去,直到与的结果是0,每次与的次数+1
时间复杂度O(1),需要检查次数=二进制数中1的个数
解题代码
第1种解法:
<<<1表示无符号位右移1位,高位补0
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
count += n & 1;
n >>> = 1;
}
return count;
}
}
第2种解法:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n!=0){
n=n&(n-1);
count ++;
}
return count;
}
}
力扣 50
Python代码解题
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0:
x = 1 / x
n = -n
pow = 1
while n:
if n & 1:
pow *= x
x *= x
n >>= 1
return pow
Java代码解题:
class Solution {
public double myPow(double x, int n) {
if(x == 0.0f) return 0.0d;
long b = n;
double res = 1.0;
if(b < 0) {
x = 1 / x;
b = -b;
}
while(b > 0) {
if((b & 1) == 1) res *= x;
x *= x;
b >>= 1;
}
return res;
}
}