Skip to content

Primitive Types

[! TIP]

  • Use bin(x) to get the binary representation of a number
  • Use mask = 0xFFFF for a 16-bit mask, or use (1 << n) - 1 to create an n-bit mask
  • Use x & (x-1) to clear the lowest bit. Use x & ~(x-1) to extract the lowest bit
  • Python bitwise operators are &, |, >>, <<, ~, ^, XOR can be very valuable
  • Use a cache or LUT to conduct expensive operations once, up front

4.7 Compute $x^y$

The trick to this one is to reduce the number of computations by relating that $x^y = x^{y_1+y_2} = x^{y_1} x^{y_2}$ so if you can compute $x^2$ or $x^4$ etc. then you can reduce the total number of multiplications to arrive at the final answer. My solution may have worked fine, that is return x ** float(y), but in an interview they may have asked for a better solution, or a less pythonic one.

4.8 Reverse Digits

The trick to this one is to notice that when you do remainder division x // 10 you get the remaining values that you still need to reverse. You can add the remainder (the result of the modulo x % 10) and continue until the division result is 0.

I was very close for this one, in fact I got the solution, albeit less elegantly than the solution in the book.

[! WARNING] Redo Redo/review 4.2, 4.3, & 4.11

LC 67 Add Binary Numbers

Solution: The key here is to understand base 2 and simply complete the summation with the associated power of 2 and return a binary formatted string.

python
def addBinary(self, a: str, b: str) -> str:

    base = 2
    new_a = 0
    for i in range(len(a)):
	    new_a += 0 if a[i] == "0" else base**(len(a) - 1 - i) 

    new_b = 0
    for i in range(len(b)):
	    new_b += 0 if b[i] == "0" else base**(len(b) - 1 - i)

    output = new_a + new_b
    return f"{output:b}"
def addBinary(self, a: str, b: str) -> str:

    base = 2
    new_a = 0
    for i in range(len(a)):
	    new_a += 0 if a[i] == "0" else base**(len(a) - 1 - i) 

    new_b = 0
    for i in range(len(b)):
	    new_b += 0 if b[i] == "0" else base**(len(b) - 1 - i)

    output = new_a + new_b
    return f"{output:b}"