Last active
November 26, 2021 10:21
-
-
Save a2br/58b3850ea3c7f85eb0364ac709daba07 to your computer and use it in GitHub Desktop.
by youcef et anatole in 2021
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add_binary_numbers(b1: str, b2: str) -> str: | |
# Déterminer plus grande longueur | |
max_length = max(len(b1), len(b2)) | |
# Égaliser | |
b1 = b1.zfill(max_length) | |
b2 = b2.zfill(max_length) | |
# Valeur de retenue | |
carry = 0 | |
# Initialise le résultat | |
result = "" | |
# Itérer pour chaque bit en commençant par la fin | |
for i in range(max_length - 1, -1, -1): | |
# Prendre en compte la retenue | |
s = carry | |
# Fait la somme des 2 bits | |
s += 1 if b1[i] == "1" else 0 | |
s += 1 if b2[i] == "1" else 0 | |
# Ajoute le bit en tête du résultat | |
result = ("1" if s % 2 == 1 else "0") + result | |
# Garde la retenue si nécessaire | |
carry = 0 if s < 2 else 1 | |
# Ajouter un bit si il reste une retenue | |
if carry != 0: result = "1" + result | |
return result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment