Integer -> 4 bytes -> 32 bits
Long -> 8 bytes -> 64 bits
Boolean/Char -> 1 byte
Given an array of integers, every element appears twice except for one. Find that single one.
def singleNumber(self, A: List[int]) -> int:
for i in range(1, len(A)):
A[i] ^= A[i-1]
return A[-1]Write a function that takes an unsigned integer and returns the number of ’1' bits it has. (also known as the Hamming weight)
def hammingWeight(self, n: int) -> int:
result = 0
for i in range(32):
result += n & 1
n >>= 1
return resultGiven an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.
Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.
n.
class Trie:
def __init__(self):
self.children = {}
class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
self.root = Trie()
for n in nums:
self.insert(n, self.root)
res = 0
for n in nums:
res = max(res, self.search(n, self.root))
return res
def insert(self, n, root):
for i in range(30, -1, -1):
cur = (n >> i) & 1
if cur not in root.children:
root.children[cur] = Trie()
root = root.children[cur]
def search(self, n, root):
pre = 0
for i in range(30, -1, -1):
cur = (n >> i) & 1
wanted = (1 - cur)
if wanted in root.children:
root = root.children[wanted]
pre += (1 << i)
else:
root = root.children[cur]
return pre