7
\$\begingroup\$

The standard long addition method:

The standard algorithm for adding multidigit numbers is to align the addends vertically and add the columns, starting from the ones column on the right. If a column exceeds ten, the extra digit is "carried" into the next column. (wikipedia)

A long addition example:

 145
+ 98
-----
 243

Backwards long addition is similar but you start adding from the leftmost column and carry to the next column (on it's right). If the last (ones) column produces a carry you write it behind the current sum in the next column. If there is no carry in the last column no extra column is needed.

 145
+ 98
-----
 1341

Explanation for the above example by columns, left to right: 1 = 1; 4+9 = 10(carried) + 3; 5+8+1(carry) = 10(carried) + 4; 1(carry) = 1

You should write a program or function which receives two positive integers as input and returns their sum using backwards long addition.

Input

  • Two positive integers.

Output

  • An integer, the sum of the two input numbers using backwards long addition.
  • There should be no leading zeros. (Consider 5+5=1 or 73+33=7.)

Examples

Format is Input => Output.

1 3 => 4          
5 5 => 1          
8 9 => 71         
22 58 => 701      
73 33 => 7        
145 98 => 1341    
999 1 => 9901     
5729 7812 => 26411
\$\endgroup\$
4
  • \$\begingroup\$ May I assume an upper bound on the decimal length of the numbers, at, say, 99 digits? \$\endgroup\$
    – xnor
    Jul 16, 2015 at 17:39
  • \$\begingroup\$ @xnor No. Your datatype can limit the largest number you can handle but your algorithm should work for arbitrary large numbers. \$\endgroup\$
    – randomra
    Jul 16, 2015 at 18:15
  • \$\begingroup\$ How would you rule on Python 2's adding an L for numbers greater than 2**31 that don't fit in an int, and so messing up the method of string reversing? \$\endgroup\$
    – xnor
    Jul 16, 2015 at 18:21
  • \$\begingroup\$ @xnor The datatype you use can represent numbers greater than 2**31 numbers so you have to deal with their representation. \$\endgroup\$
    – randomra
    Jul 16, 2015 at 18:43

12 Answers 12

8
\$\begingroup\$

Pyth, 16 bytes

Still new to Pyth, but this looks promising..

s_`smvs.[_d0lzcz

The idea here is simple. To do backwards addition, you need backwards numbers. We take the input, reverse it, make sure that it has same number of digits be adding trailing 0, sum the two numbers, reverse it again and make sure no leading zero exists.

Code expansion

              cz          # Take the input and Python split it. Splits on space automatically
    m                     # Now we map over these two strings
         _d               # Reverse the string
       .[  0lz            # Pad it with 0 on right so that its length is same as input length
     vs                   # We have array of character and number, stringify and eval
   s                      # Sum the numbers in array
  `                       # Stringify
 _                        # Reverse
s                         # Convert back to number, removing leading 0

Try it online here

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Careful, CJam is going to get jealous. \$\endgroup\$
    – Alex A.
    Jul 16, 2015 at 14:35
  • \$\begingroup\$ Don't worry, I am still writing in CJam and then translating. CJam will always be my first ;) \$\endgroup\$
    – Optimizer
    Jul 16, 2015 at 15:02
  • \$\begingroup\$ Oh good, I was really worried there for a minute! \$\endgroup\$
    – Alex A.
    Jul 16, 2015 at 15:16
3
\$\begingroup\$

Python 2, 80 78 Bytes

I didn't intend to have to reverse at the end, but apparently I need to.. I will fix this (maybe)!

Thanks to Alex A. for saving 2 bytes, and flornquake for saving 3 bytes!

a,b=input();s=0
while a+b:s=s*10+a%10+b%10;a/=10;b/=10
print int(str(s)[::-1])

Input like so: num1, num2.

\$\endgroup\$
3
  • \$\begingroup\$ a or b can be turned into a+b. \$\endgroup\$
    – flornquake
    Jul 16, 2015 at 17:28
  • \$\begingroup\$ @randomra Simple fix is to use str(s) instead of `s` \$\endgroup\$
    – mbomb007
    Jul 16, 2015 at 18:56
  • \$\begingroup\$ @randomra fixed. \$\endgroup\$
    – Kade
    Jul 16, 2015 at 18:57
3
\$\begingroup\$

CJam, 22 bytes

q:QS/{W%Q,0e]s~}/+sW%~

This is pretty much the same algorithm as the Pyth answer, just a bit longer due to different syntax.

Code expansion

q:Q                     e# Read the input and store it in Q
   S/                   e# Split the input on space.
     {         }/       e# Now we map over the two values in the array
      W%                e# Reverse the number treating it like a string
        Q,0e]           e# Right pad it with enough 0 to make its length same as input
             s~         e# Convert to string and evaluate to get integer
                 +s     e# Sum the two numbers and convert the sum to string
                   W%~  e# Reverse the sum as a string and evaluate to remove leading 0

Try it online here

\$\endgroup\$
1
  • \$\begingroup\$ 21 bytes with command-line arguments: ea{W%eas,0e]s~}/+sW%~ \$\endgroup\$
    – Dennis
    Jul 17, 2015 at 4:15
3
\$\begingroup\$

CJam, 26 bytes

This is the first time I'm using CJam, I don't know many operators yet so it's surely sub-optimal. Gotta start somewhere :)

l~]$~s_,@s\0e[sW%i\W%i+sW%

Try it online.

Ungolfed:

l~    e# Takes input
]$~   e# Wrap in array, sort and unwrap
s_,   e# Convert highest to string, push length
@s\   e# Setup stack for padding (["hi" "lo" len])
0e[s  e# Left pad with zeroes and convert to string
W%i\  e# Reverse digits, convert to int, swap stack
W%i+  e# Reverse digits, convert to int, sum
sW%   e# Convert result to string and reverse digits
      e# Stack is automatically printed
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice solution, but particularly impressive given that it's your first time with CJam. \$\endgroup\$
    – Alex A.
    Jul 16, 2015 at 17:56
2
\$\begingroup\$

Bash + coreutils, 62

Not sure if this counts or not, but it does give the right answers (for 32-bit integers):

r()(printf %09d#01 $1|rev)
rev<<<$[`r $1`+`r $2`]|sed s/^0\*//

Test output:

$ for t in "1 3" "5 5" "8 9" "22 58" "73 33" "145 98" "999 1" "5729 7812"
do ./backlongadd.sh $t; done
4
1
71
701
7
1341
9901
26411
$
\$\endgroup\$
2
  • \$\begingroup\$ @randomra my implementation of the algorithm felt a little cheaty - basically rev( rev(a) + rev(b) ) with some carefully placed zeroes - instead of doing all the carries and whatnot manually). But if its OK with you, then its OK with me :) \$\endgroup\$ Jul 16, 2015 at 16:24
  • 1
    \$\begingroup\$ That's perfectly fine. Just the output matters, not the method. My wording probably wasn't the best but haven't found better. \$\endgroup\$
    – randomra
    Jul 16, 2015 at 16:28
1
\$\begingroup\$

Java, 337 312 bytes

Not quite a golfed language or solution, but it at least works and was fun to write. There's quite a few byte penalties to this approach, but I'm mostly happy with it.

void g(int a,int b){String p=(a>b?a:b)+"",o=(a>b?b:a)+"",s="";int m=p.length(),i=0,c=0,t;for(;i++<m;)o=(o.length()==m?"":"0")+o;for(i=-1;i++<m-1;){t=Integer.parseInt(p.charAt(i)+"")+Integer.parseInt(o.charAt(i)+"")+c;c=0;if(t>9){c=1;t=Integer.parseInt((t+"").charAt(1)+"");}s+=t;}System.out.print(s+(c>0?c:""));}

Input/Output:

g(8,9)    --> 71
g(145,98) --> 1341
g(999,1)  --> 9901

Spaced and tabbed out:

void g(int a,int b){

    String p=(a>b?a:b)+"",
      o=(a>b?b:a)+"",
      s="";

    int m=p.length(),
      i=0,
      c=0,
      t;

    for(;i++<m;)
      o=(o.length()==m?"":"0")+o;


    for(i=-1;i++<m-1;){
      t=Integer.parseInt(p.charAt(i)+"")+Integer.parseInt(o.charAt(i)+"")+c;
      c=0;
      if(t>9){
        c=1;
        t=Integer.parseInt((t+"").charAt(1)+"");
      }
      s+=t;
    }
    System.out.print(s+(c>0?c:""));
  }
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Tips: 1) You can save a few on Math.min/max by using a ternary like (a>b?a:b)+""; instead. 2) static is not generally required for functions here, unless you're doing something odd where it really does need to be static. 3) Get rid of the braces on the first for block, they're not needed for a single statement. 4) I don't think you need to initialize t in the declaration, since it's never used before initialization. 5) You can lose the parentheses around c>0 in the return and o.length()==m above. 6) I don't think you need a newline, so just use print instead of println. \$\endgroup\$
    – Geobits
    Jul 16, 2015 at 17:55
  • 1
    \$\begingroup\$ @Geobits Thank you! I hadn't even thought of using ternary ops, always wondered about the static deceleration, and glad you caught the other stuff \$\endgroup\$
    – DeadChex
    Jul 16, 2015 at 18:41
1
\$\begingroup\$

O, 22 bytes

ii`\`e@e@\-{0+}d#\#+`o

Padding zeros, can be golfed a lot.

\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6), 112 bytes

g=(a,b,r=z=>+[...z].reverse().join``,x=(a<b?a:b)+'')=>r(r(y=(a<b?b:a)+'')+r('0'.repeat(y.length-x.length)+x)+'')

Algorithm

  1. Determine the smaller number (x)
  2. Pads x with leading zeroes up to the length of the bigger number y
  3. Reverse both strings, cast to integer, add them together and convert it back to a string
  4. Reverse that string and cast to integer to get rid of leading zeroes

Demo

As with all ES6 code, it only works in Firefox at time of writing:

g=(a,b,r=z=>+[...z].reverse().join``,x=(a<b?a:b)+'')=>r(r(y=(a<b?b:a)+'')+r('0'.repeat(y.length-x.length)+x)+'')

// For demonstration purposes
console.log = x => X.innerHTML += x + '\n';

console.log(g(1,3));
console.log(g(5,5))
console.log(g(8,9))
console.log(g(22,58))
console.log(g(73,33))
console.log(g(145,98))
console.log(g(999,1))
console.log(g(5729,7812))
<pre><output id=X></output></pre>

\$\endgroup\$
0
\$\begingroup\$

Julia, 190 173 163 160 bytes

f(a,b)=(n=ndigits;d=digits;m=max(n(a),n(b));C=reverse([0,d(a,10,m).+d(b,10,m)]);for i=1:m C[i+1]+=C[i]÷10;C[i]=C[i]%10end;c=join(C);int(c[end]=='0'?chop(c):c))

This creates a function f that accepts two integers and returns an integer.

Ungolfed + explanation:

function f(a,b)
    # Determine the maximum number of digits between a and b
    m = max(ndigits(a), ndigits(b))

    # Create an array as the elementwise sum of the digits of
    # a and b with a single trailing 0, where the digit arrays
    # are left padded with zeros to each have length m
    C = reverse([0, digits(a, 10, m) .+ digits(b, 10, m)])

    # Carry digits as necessary
    for i = 1:m
        C[i+1] += C[i] ÷ 10
        C[i] = C[i] % 10
    end

    # Join the array into a string
    c = join(C)

    # If the string has a trailing zero, lop it off, then
    # convert the string to an integer and return it
    int(c[end] == '0' ? chop(c) : c)
end
\$\endgroup\$
0
\$\begingroup\$

PHP, 112 bytes

Same algorithm as my JavaScript answer. It's sad that PHP has the same amount of chars (unless my other answer can be golfed further). Then again, the built-in string functions and implicit conversions really helped.

function g($a,$b,$r='strrev'){echo$r($r($y=max($a,$b))+$r(str_pad($x=min($a,$b),strlen($y)-strlen($x),0,0)))+0;}

Unminified:

function g($a, $b) {
    $y = max($a,$b);
    $x = min($a,$b);
    echo strrev(strrev($y) + strrev(str_pad($x, strlen($y) - strlen($x), 0, STR_PAD_LEFT))) + 0;
}
\$\endgroup\$
0
\$\begingroup\$

Python 3, 92 bytes

For what it's worth (if anything), this function accepts an arbitrary number of inputs and adds them all.

r=lambda *a:int(str(sum(map(int,(format(n,'0>'+str(len(str(max(a)))))[::-1]for
n in a))))[::-1])

Ungolfed version:

def rsum(*summands):
    l = len(str(max(summands)))
    fmt = '0>' + str(l)
    reverse_summands = (format(n, fmt)[::-1] for n in summands)
    reverse_sum = sum(int(nrev) for nrev in reverse_summands)
    return int(str(reverse_sum)[::-1])

It's the same approach as Digital Trauma's answer: pad the shorter number with leading zeroes, reverse them, add them, and reverse the sum. The bulk of the code is int-to-string-to-int-to... conversion.

\$\endgroup\$
0
\$\begingroup\$

Pyth, 17 bytes

s_`isM.TmsMdc_z)T

An alternative method without 0 padding.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.