[Bit Operations-Simple] Interview Question 16.07. Maximum Value

[Title]
Write a method to find the largest of the two numbers a and b. Do not use if-else or other comparison operators.
[Example]
Input: a = 1, b = 2
Output: 2
[Code]
[Python]
Insert picture description here

class Solution:
    def maximum(self, a: int, b: int) -> int:
        return (a+b+abs(a-b))//2

【Abnormal Dafa】
Insert picture description here

class Solution:
    def maximum(self, a: int, b: int) -> int:
        try:
            int(str(a - b)[0])
        except:
            return b
        return a

[The best way]
1. Look at the return statement first, if k=0, the return value is a; if k=1, the return value is b; that is, if a>b, I should set k=0, otherwise Let k=1. The question now is how to determine the value of k?
2. Then look at the first and second lines. You need to understand the storage method of the int type first, which can be found on the Internet. After understanding, continue to look: because both a and b are int, that is, in the interval of [-2 32 ,2 32 -1], it can be determined that ab is in the interval of (-2 33 ,2 33 -1).
2.1 If ab<0, then the 33 digits from the left of ab must be 1, so 2 33 and ab perform an AND operation to get 2 33 , which is recorded in k. Shift k to the right by 33 bits to get
1.2.2. Otherwise, ab>0, then the 33 bits from the left of ab must be 0. At this time, the value of k is 0.
Combine step 2 and step 1 to get the answer.

class Solution:
    def maximum(self, a: int, b: int) -> int:
        k=(a-b)&(2**33)
        k=k>>33
        return k*b+a*(k^1)

【3】

class Solution:
    def maximum(self, a: int, b: int) -> int:        
        k=((a-b)>>32)&1
        return k*b+a*(k^1)

Guess you like

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