位运算和==vs!=操作

2024-04-26 22:35:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在处理一些Leetcode问题时遇到了一个奇怪的问题:

for i in range(32):
        if(n&mask == 1):
            bits +=1
        mask <<=1
    return bits

这不管用。现在,如果不是比较它是否等于1,而是在它不同于0时做条件,它就起作用了。你知道吗

for i in range(32):
        if(n&mask != 0):
            bits +=1
        mask <<=1
    return bits

他们不是用不同的方式做同样的事情吗?答案不应该是一样的吗?下面的问题(https://leetcode.com/problems/number-of-1-bits/description/


Tags: 答案inhttpscomforreturnif方式
2条回答

不,它们和你发现的不一样。听起来很明显,==1检查值是否为1,!=0检查值是否与0不同。您可能缺少的是1和0以外的值是可能的。你知道吗

a&b返回2个整数的位与:1&1 == 1,但是2&2 == 2,因此2&2 != 0,但是不是1。你知道吗

and , or , not& , | , !之间存在差异

and、or、not是逻辑运算符,& , | , !是位运算符。你知道吗

x or y:如果x为假,那么y为假,否则x为假

x and y:如果x为假,则x为假,否则y为假

not x:如果x为假,则为真,否则为假

快捷方式:

x and y:如果两者都不是假,则总是给出y

x or y:如果两者都不是假,则总是给出x

What is actually false ?

来自官方文件:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a nonzero() or len() method, when that method returns the integer zero or bool value False.2.5
  • All other values are considered true so objects of many types are always true.

除非另有说明,否则具有布尔结果的操作和内置函数总是返回0或False表示False,返回1或True表示True。(重要的例外:布尔运算“or”和“and”总是返回其中一个操作数。)

什么是位运算符?你知道吗

位运算符用于位操作和加法:

|运算符不是加法(它在真值表上执行加法) &;运算符不是乘法(它基于真值表执行乘法)

5 | 3=>;101 | 011=111,十进制为7

5&;3=>;101&011=001,即1

您可以在python终端中检查这些

相关问题 更多 >