سؤال

How to sum 2 numbers digit by digit with pseudo code?

Note: You don't know the length of the numbers - if it has tens, hundreds, thousands... Units should be add to units, tens to tens, hundreds to hundreds..... If there is a value >= 10 in adding the units you need to put the value of that ten with "the tens"....

I tried

Start

Do

Add digit(x) in A to Sum(x)

Add digit(x) in B to Sum(x)

If Sum(x) > 9, then (?????)

digit(x) = digit(x+1)

while digit(x) in A and digit(x) in B is > 0

  • How to show the result?

I am lost with that.....

Please help!

هل كانت مفيدة؟

المحلول

Try this,

 

n = minDigit(a, b) where a and b are the numbers.
let sum be a number.

m = maxDigit(a,b)
allocate maxDigit(a,b) + 1 memory for sum

carry = 0;

for (i = 1 to n)     
    temp = a[i] + b[i] + carry
    // reset carry
    carry = 0
    if (temp > 10) 
        carry = 1
        temp = temp - 10;

    sum[i] = temp

// one last step to get the leftover carry

if (digits(a) == digits(b) 
    sum[n + 1] = carry
    return

if (digits(a) > digits(b)
    toCopy = a
else
    toCopy = b

for (i = n to m)
    temp = toCopy[i] + carry
    // reset carry
    carry = 0
    if (temp > 10) 
        carry = 1
        temp = temp - 10;

    sum[i] = temp

 

Let me know if it helps

نصائح أخرى

A and B are the integers you want to sum.

Note that the while loop ends when all the three integers are equal to zero.

carry = 0
sum = 0
d = 1
while (A > 0 or B > 0 or carry > 0)
    tmp = carry + A mod 10 + B mod 10
    sum = sum + (tmp mod 10) * d
    carry = tmp / 10
    d = d * 10
    A = A / 10
    B = B / 10
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top