+ 1

# Sum of binary numbers

I have to write this code : the inputs are two binary numbers (for example: 101 and 010) and the output has to be the binary sum of those two numbers ( 111) . I'm not allowed to use any built-in function for this exercise and the things I can use are while-for loop

5 Answers

+ 2

Nikki,
It doesn't matter, what matters is all the digits are valid for the number base, for binary this means there should be no digits greater than 1.
Assuming you take the inputs as string and you made sure all digits are valid. Measure the length of the string. Per your example '101' length is 3. Now you calculate 2 raised to the power of length - 1. Thats 2 ** (3 - 1) => 4 (the multiplier)
Then you run through the string from the beginning using a loop. Divide the multiplier by 2 on each loop iteration
digit multiplier result
1 * 4 4
0 * 2 0
1 * 1 1
So far you get it right?

+ 2

Yes I got it
Thank you so muchhh !
Ipang

+ 2

Okay good luck with the code đ

+ 1

Do you know how to convert binary number into decimal? I think you need to research on that subject to solve this.

+ 1

Yes I know how . But what if the binary number starts with zero ? How can I convert it into decimal then ? Ipang