zoukankan      html  css  js  c++  java
  • 算法--leetcode 461. Hamming Distance in Python

    题目:

    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.

    两个数的二进制表达式中 对应位不同的位的个数(异或运算)

    Python 解决:

    主要使用自带库函数,bin()表示将一个数转变为二进制,count(‘1’)计数 1 出现的个数

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

    C++解决:

    思路:直接将两数或运算,然后使用exc&=(exc-1)的方式 移除最右边的1,直到循环到exc为0

    class Solution {
        public:
        int hammingDistance(int x, int y) 
        {
            int res=0;
            int exc=x^y;
            while(exc)
            {
                ++res;
                exc &= (exc - 1);
            }
            return res;
        }
    };
  • 相关阅读:
    愚公移山
    唐雎不辱使命
    渡易水歌
    论语
    智子疑邻
    学弈
    SQL Merge 语法 单表查询
    大道之行也
    Java开发人员最常犯的10个错误
    模拟Spring手撕一个简单的IOC容器
  • 原文地址:https://www.cnblogs.com/derek-dhw/p/8040129.html
Copyright © 2011-2022 走看看