[Bit Operation-Simple] Interview Question 05.06. Integer Conversion

[Topic]
Integer conversion. Write a function to determine how many bits need to be changed to convert integer A to integer B.
[Example 1]
Input: A = 29 (or 0b11101), B = 15 (or 0b01111)
Output: 2
[Example 2]
Input: A = 1, B = 2
Output: 2
[Prompt]
A, B range is [- 2147483648, 2147483647]
[Code]
[Python]
Insert picture description here

class Solution:
    def convertInteger(self, A: int, B: int) -> int:
        cnt=0
        for i in range(32):
            if A&1!=B&1:
                cnt+=1
            A>>=1
            B>>=1
        return cnt

Guess you like

Origin blog.csdn.net/kz_java/article/details/115122563