iT邦幫忙

0

leetcode with python:461. Hamming Distance

  • 分享至 

  • xImage
  •  

題目:

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

Given two integers x and y, return the Hamming distance between them.

給定兩數,回傳它們的Hamming distance
Hamming distance表兩數二進位表示時有幾位值不同
ex:1(001)和4(100),它們第一位和第三位值不同,有兩位不同
所以它們的Hamming distance為2

這題用到位元運算的概念

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        t=x^y
        cnt=0
        while t:
            if t&1:
                cnt=cnt+1
            t=t>>1
        return cnt

用^運算,兩數不同值的位數會以1表示
如1(001)和4(100),會變為5(101)
我們只要計算運算結果的二進位表示有幾個1即可
數1的方式類似191.的法一
最後執行時間29ms(faster than 96.03%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言