美文网首页
python 按位运算符

python 按位运算符

作者: 聪民 | 来源:发表于2019-12-03 22:37 被阅读0次

刷leetcode刷到一道题,看到discussions里面有一个挺聪明的解法,记录一下。

136. Single Number
Given anon-emptyarray of integers, every element appearstwiceexcept for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input:[2,2,1]Output:1
Example 2:
Input:[4,1,2,1,2]Output:4

我的方法是用字典保存了所有出现过的数字出现的次数,取value为1的那一个。

import collections
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        d = collections.Counter(nums)
        for key in d:
            if d[key] == 1:
                return key

按位运算符:python的位运算符是基于其数值化为二进制的0 1bit后再进行的运算;需要注意的是其返回结果为10进制形式。

^:按位异或运算符,相同取1,不同取0;
~:按位取反运算符,0变为1,1变为0;
|:按位或运算符,1和0组合为1,纯0或纯1为0;
&:按位与运算符,只有全是1的时候才为1,只要有一个0为0。

于是就可以写成这样

def singleNumber(self, nums):
    res =0
    for num in nums:
        res ^= num
return res

相关文章

  • python运算符

    Python算数运算符 Python比较运算符 Python赋值运算符 Python位运算符 按位运算符是把数字看...

  • 基础运算符

    [使1. 按位与运算符(&](#1. 按位与运算符(&)[按位或运算符 | ](#2. 按位或运算符(|)) 1....

  • python 按位运算符

    刷leetcode刷到一道题,看到discussions里面有一个挺聪明的解法,记录一下。 我的方法是用字典保存了...

  • 高级运算符(Advanced Operators)

    目录 [toc] 位运算符 1. 按位取反运算符~ 2. 按位与运算符& 3. 按位或运算符| 4. 按位异或运算...

  • 高级运算符

    1:位运算 1.1:按位取反运算符(~) 例子 1.2:按位与运算符 例子 1.3:按位或运算符 例子 1.4:按...

  • 位运算符

    按位运算符有6个 & 按位与| 按位或^按位异或~取反>>右移<<左移 1 、& 运算符 &是二元运算符,它以特定...

  • C、数据结构知识点

    1. 位运算符有: &(按位与)、|(按位或)、^(按位异或)、~ (按位取反)。 其中,按位取反运算符是单目运算...

  • 开发基础随笔之位运算符(Bitwise Operators)

    位运算符,属于算术运算符 按位逻辑运算符: 位移运算符: 位运算符的运算数只能是整数 位移运算符:按位左移 a<<...

  • C语言-按位逻辑运算符和位移运算符

    按位逻辑运算符 按位与运算符(bitwise AND operator) a & b 按位计算a和b的逻辑与; 按...

  • 理解C语言位运算符

    位运算符 位运算符包括:& 、|、^、~、<<、>> 分析 & 按位与操作,按二进制位进行"与"运算。| 按位或运...

网友评论

      本文标题:python 按位运算符

      本文链接:https://www.haomeiwen.com/subject/wnnhgctx.html