算法篇之(位运算)

前言:位移运算就是二进制,位移进行左移或右移操作,其不需要转换成十进制,处理速度很快,位移运算符在算法方面也有应用,力扣上找了几道题练习位运算。

目录

思维导图:

力扣191

思路:

解题代码

力扣 50


思维导图:

力扣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;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MRJJ_9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值