Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
We have been give a problem to add two numbers without the + operator and using XOR, AND and <<.
Our job is to find the total number of iterations that while loop is going to take.

What I have tried:

Python
<pre>
from sys import stdin,stdout
T = int(stdin.readline().strip())
for itr_t in range(T):
    a = (stdin.readline().strip(),2)
    b = (stdin.readline().strip(),2)
    print(a)
    print(b)
    count = 0
    while b != 0:
                count += 1
                u = a^b
                v = a&b
                a = u
                b = v << 1
    print(count)


So i just used a basic counter but I want to optimise it and want to find the count without actually doing the operations over and over again.
My logic is that count = to the number of times the carry will be shifted
But I would really like some hint/advice on this one to apply a better a logic to find the count. I believe the complexity is O(1).
I know I tried this in python but I'm fine with C++ as well
Posted
Updated 8-Dec-19 6:06am
v2
Comments
PIEBALDconsult 8-Dec-19 19:05pm    
# define add +

Done.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900