+ 3

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?

29th Apr 2021, 10:12 AM
Marjaf - avatar
9 Answers
+ 9
You 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.
29th Apr 2021, 1:25 PM
Mirielle - avatar
+ 6
29th Apr 2021, 11:57 AM
Oma Falk
Oma Falk - avatar
+ 4
+ is not allowed? How about -(-number), number.__add__(number) or sum(list) ?
29th Apr 2021, 10:35 AM
CarrieForle - avatar
+ 1
It should be quite easy to sum up binary decimals without + operator if you just can convert the numbers to binary.
29th Apr 2021, 12:18 PM
Seb TheS
Seb TheS - avatar
+ 1
U can use either concatenation r else use append
1st May 2021, 6:19 AM
Bindhu Shree G
Bindhu Shree G - avatar
(,) concatenation can used
30th Apr 2021, 4:32 AM
Rohith Paul Mathew
Rohith Paul Mathew - avatar
CarrieForle no sum, -(-) ,... is not allowed too😓
30th Apr 2021, 8:22 AM
Marjaf - avatar
30th Apr 2021, 8:24 AM
Marjaf - avatar
You can tickmark the answer you liked as the solution. That'll help people looking for the same answer.
1st May 2021, 2:17 AM
Sheikh - avatar