# Add Numbers without using "+"

Hi I have to write a program that, for example takes an input, like this: 2 + 4 + 20 + 4+.... and displays the binary equivalent of their sum in the output. and I'm not allowed to use + to add Numbers in the program. I can only use + in the input itself. can anyone give me an idea to solve?

4/29/2021 10:12:52 AM

Marjaf9 Answers

New AnswerYou can look at each bits in a loop untill either operand << value is 0. for two operands A and B. 1. create a local variable Z that hold the carry out from each bits of A and B z = A & B 2. make A the result of the XOR (A ^ B) this could be addition without carry A = A ^ B 3. make B the result of carryIn for each bit such that B = Z << 1 def add(x, y): while y: z = x & y x = x ^ y y = z << 1 return x The loop keeps adding the carry until the carry is 0 for all bits. print(add(-3, -2)). // -5 print(add(3, 3)) // 6 However, there's a drawback in this method when either of the operand is "unsigned" and that would result to an undefined behavior. print(add(3, -2)) //undefined Well this make senses due to the way the left-shift operator is handled in Python. Instead of reaching an upper limit on the integer bits, and setting the highest bit to make a number negative, it becomes positive long integers.

It should be quite easy to sum up binary decimals without + operator if you just can convert the numbers to binary.

You can tickmark the answer you liked as the solution. That'll help people looking for the same answer.