Skip to the content.

Binary and Logic Gates Hacks

Tri 3 Team Teach Hacks

Popcorn Hack 1

  • Example 1: Binary
  • Example 2: Not Binary
  • Example 3: Binary

Popcorn Hack 2

  • 101 + 110 = 1011
  • 1101 - 1011 = 010
  • 111 + 1001 = 1110

Popcorn Hack 3, 4, 5

  • False
  • False
  • True

Homework Hack 1

def decimal_to_binary(decimal_num):
    # Handle zero edge case
    if decimal_num == 0:
        return "0"
    is_negative = decimal_num < 0
    decimal_num = abs(decimal_num)
    
    binary_str = ""
    while decimal_num > 0:
        binary_str = str(decimal_num % 2) + binary_str
        decimal_num //= 2
    
    return "-" + binary_str if is_negative else binary_str


def binary_to_decimal(binary_str):
    is_negative = binary_str.startswith('-')
    if is_negative:
        binary_str = binary_str[1:]

    decimal_num = 0
    for i, bit in enumerate(reversed(binary_str)):
        if bit not in ('0', '1'):
            raise ValueError("Binary string must contain only 0s and 1s")
        decimal_num += int(bit) * (2 ** i)

    return -decimal_num if is_negative else decimal_num


# πŸ” Test cases
test_decimals = [10, -10, 0, 255, -255]
test_binaries = ["1010", "-1010", "0", "11111111", "-11111111"]

print("πŸ“₯ Decimal to Binary:")
for num in test_decimals:
    print(f"{num} β†’ {decimal_to_binary(num)}")

print("\nπŸ“€ Binary to Decimal:")
for bstr in test_binaries:
    print(f"{bstr} β†’ {binary_to_decimal(bstr)}")
πŸ“₯ Decimal to Binary:
10 β†’ 1010
-10 β†’ -1010
0 β†’ 0
255 β†’ 11111111
-255 β†’ -11111111

πŸ“€ Binary to Decimal:
1010 β†’ 10
-1010 β†’ -10
0 β†’ 0
11111111 β†’ 255
-11111111 β†’ -255

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)

βœ… Difficulty set to: medium