简体   繁体   中英

Bit operations and the == vs != operator

I'm doing some Leetcode problems and I came across a weird problem:

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

This doesn't work. Now if instead of comparing if it is equal to one do the condition when it's different than 0, it works.

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

Aren't they doing the same thing in a different way? Shouldn't the answer be the same? The questions in the following ( https://leetcode.com/problems/number-of-1-bits/description/ )

No, they are not the same, as you discovered. As obvious as it sounds, ==1 checks if the value is 1, !=0 check if the value is different from 0. What you are probably missing is that values other than 1 and 0 are possible.

a&b returns the bitwise and of 2 integers: 1&1 == 1 , but 2&2 == 2 , and thus 2&2 != 0 , but is not 1.

There is difference between and , or , not and & , | , ! & , | , !

and , or , not are logical operators and & , | , ! & , | , ! are bitwise operators.

x or y : if x is false then y , else x

x and y : if x is false then x , else y

not x : if x is false then true else false

Shortcut :

x and y : always gives y if both are not false

x or y : always gives x if both are not false

What is actually false ?

From python official doc :

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.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations "or" and "and" always return one of their operands.)

Now what are bitwise operators?

Bitwise operators work on bit manipulation and addition :

| operator is not addition ( it perform addition basis on truth table) & operator is not multiplication (it perform multiplication basis on truth table)

5 | 3 => 101 | 011 = 111 which is 7 in decimal

5 & 3 => 101 & 011 = 001 which is 1

You can check these in python terminal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM