Skip to the content.

Base 2 Math and Logic Gates

Popcorn Hack 1:

  • Ex. 1: Yes, it is binary
  • Ex. 2: No, it’s not binary
  • Ex. 3: Yes, it is binary

Popcorn Hack 2:

  • Ex. 1: 1101
  • Ex. 2: 010
  • Ex. 3: 1110

Popcorn Hack

  • 1.2: true
  • 2.2: false
  • 3.2: true

Homework hack 1

 ```
def decimal_to_binary(decimal):
    """Converts a decimal number to binary (supports negatives)."""
    if decimal == 0:
        return "0"
    is_negative = decimal < 0
    decimal = abs(decimal)
    binary = ""
    while decimal > 0:
        binary = str(decimal % 2) + binary
        decimal //= 2
    return "-" + binary if is_negative else binary

def binary_to_decimal(binary_str):
    """Converts a binary string to a decimal number (supports negatives)."""
    is_negative = binary_str.startswith("-")
    if is_negative:
        binary_str = binary_str[1:]
    decimal = 0
    for digit in binary_str:
        decimal = decimal * 2 + int(digit)
    return -decimal if is_negative else decimal

# Test cases
print("Decimal to Binary:")
print("10 ->", decimal_to_binary(10))       # 1010
print("-10 ->", decimal_to_binary(-10))     # -1010
print("0 ->", decimal_to_binary(0))         # 0

print("\nBinary to Decimal:")
print("1010 ->", binary_to_decimal("1010"))       # 10
print("-1010 ->", binary_to_decimal("-1010"))     # -10
print("0 ->", binary_to_decimal("0"))             # 0
```

Homework hack 2

```
import time

valid_difficulties = ["easy", "medium", "hard"]
difficulty = input("Enter difficulty (easy, medium, hard): ").lower().strip()

while difficulty not in valid_difficulties:
    print("Please enter a valid difficulty level.")
    time.sleep(0.5)
    difficulty = input("Enter difficulty (easy, medium, hard): ").lower().strip()

print("Difficulty set to:", difficulty)
```