Leetcode 20191225

Dec 25, 2019

Bitwise operators

371. Sum of Two Integers

https://leetcode.com/problems/sum-of-two-integers/description/

class Solution:
  def getSum(self, a, b):
    maximum = 0xffffffff
    rev = False
    if a >> 31 != 0 and b >> 31 != 0:
      rev = True
    while a & b != 0:
      i = a
      a = (a & b) << 1 & maximum
      b = (i ^ b) & maximum
    if rev:
      return ~(a ^ b ^ maximum)
    else:
      return a ^ b

28 ms 12.8 MB

37. Single Number II

https://leetcode.com/problems/single-number-ii/description/

class Solution:

[back]