MSB aligned addition

332 views Asked by At

I'm looking for a way (preferably recursive) to add two integers with their msb aligned.

For example: 125 + 25 = 375.

I tried to reverse the digits to effectively align them but the carrying would be all wrong. ie. 526 (625) + 05 (50) = 531.

2

There are 2 answers

1
user On BEST ANSWER

1) Calculate number of digits of both numbers using a while / 10 loop

2) Get the difference

3) Multiply smallest number by 10 ^ difference

4) Add them together

0
Jeremy Kahan On

you will need to include math.h for this. Assuming m and n are natural numbers, the below works by multiplying the smaller number by 10 (if needed) until it has the same number of digits as the larger, then adding.

int funkyAdd (int m, int n)
{
    if ((m<=0)||(n<=0)){return -1;}
    int smaller=std::min(m,n);
    int larger=std::max(m,n);
    while (floor(log10(smaller))<floor(log10(larger))){smaller*=10;};
    return (smaller+larger);
}