LeetCode-461. Hamming Distance-位运算

来源:互联网 发布:263网络会议室 编辑:程序博客网 时间:2024/05/29 10:56

题目:

 The Hamming distance between two integers is the number of positions at which the corresponding bits are different.


Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑

The above arrows point to positions where the corresponding bits are different.


解答:

class Solution(object):    def hammingDistance(self, x, y):        """        :type x: int        :type y: int        :rtype: int        """        return bin(x^y).count('1')


知识点:

1、bin()

bin(x)

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an__index__() method that returns an integer.

将整数转换为二进制字符串


https://docs.python.org/2/library/functions.html#bin


2、位运算

运算符描述实例&按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0(a & b) 输出结果 12 ,二进制解释: 0000 1100|按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。(a | b) 输出结果 61 ,二进制解释: 0011 1101^按位异或运算符:当两对应的二进位相异时,结果为1 (a ^ b) 输出结果 49 ,二进制解释: 0011 0001~按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。~x 类似于 -x-1(~a ) 输出结果 -61 ,二进制解释: 1100 0011,在一个有符号二进制数的补码形式。<<左移动运算符:运算数的各二进位全部左移若干位,由 << 右边的数字指定了移动的位数,高位丢弃,低位补0。a << 2 输出结果 240 ,二进制解释: 1111 0000>>右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,>> 右边的数字指定了移动的位数 a >> 2 输出结果 15 ,二进制解释: 0000 1111


http://www.runoob.com/python/python-operators.html


原创粉丝点击