def add_binary(str1, str2): result = [] # To store the binary sum carry = 0 # To keep track of the carry during addition # Initialize pointers to the end of the binary strings ptr1 = len(str1) - 1 ptr2 = len(str2) - 1 # Iterate through the binary strings from right to left while ptr1 >= 0 or ptr2 >= 0: # Get digits(0 or 1) from strings at pointers positions, # if either pointer goes beyond the string’s length, then 0 is used. if ptr1 >= 0: digit1 = ord(str1[ptr1]) - ord('0') else: digit1 = 0 if ptr2 >= 0: digit2 = ord(str2[ptr2]) - ord('0') else: digit2 = 0 # Calculate the sum of current digits and carry total_sum = digit1 + digit2 + carry # Calculate the current digit value (0 or 1) current_digit = total_sum % 2 # Update the carry for the next iteration carry = total_sum // 2 # Add the current digit to the result result.append(current_digit) # Move the pointers to the left ptr1 -= 1 ptr2 -= 1 # If there's still a carry left, add it to the result if carry: result.append(carry) # Reverse the result list reversed_result = result[::-1] # Convert each digit in the result list to a string and join them binary_sum = ''.join(str(digit) for digit in reversed_result) return binary_sum def main(): str1_list = ["1100", "1010100", "10101", "1111", "10101100110010101"] str2_list = ["0011", "0100011", "01010", "11111", "1011001010110010100"] for i in range(len(str1_list)): print(str(i+1) + ".\tFirst input string: ",str1_list[i]) print("\tSecond input string: ",str2_list[i]) print("\tBinary Sum: ", add_binary(str1_list[i],str2_list[i])) print('-'*100); if __name__ == '__main__': main()