Skip to main content
better explanation
Source Link
seshoumara
  • 3.8k
  • 1
  • 14
  • 31

Bash + coreutils, 16 bytes

xargs|tr \ +|bc 

Try it online!

There are two spaces after the \. This works for negative numbers as well.

Explanation:

xargs # known trick to turn newlines into spaces, while adding a  #trailing newline when printing the result (needed for bc) |tr \ + # turn spaces into '+'s |bc # calculates the sum 

You may wonder why tr \\n +|bc isn't better, since it turns newlines directly into '+'s. Well, that has 2 unforeseen errors:

  • if the input has a trailing newline, then it is converted to a trailing '+', hence there is no number after it to perform the addition
  • and the most weird issue is that bc requires a trailing newline after the input, but you just replaced all of the input newlines with '+'s.

Bash + coreutils, 16 bytes

xargs|tr \ +|bc 

Try it online!

There are two spaces after the \. This works for negative numbers as well.

Explanation:

xargs # known trick to turn newlines into spaces |tr \ + # turn spaces into '+'s |bc # calculates the sum 

Bash + coreutils, 16 bytes

xargs|tr \ +|bc 

Try it online!

There are two spaces after the \. This works for negative numbers as well.

Explanation:

xargs # known trick to turn newlines into spaces, while adding a  #trailing newline when printing the result (needed for bc) |tr \ + # turn spaces into '+'s |bc # calculates the sum 

You may wonder why tr \\n +|bc isn't better, since it turns newlines directly into '+'s. Well, that has 2 unforeseen errors:

  • if the input has a trailing newline, then it is converted to a trailing '+', hence there is no number after it to perform the addition
  • and the most weird issue is that bc requires a trailing newline after the input, but you just replaced all of the input newlines with '+'s.
better explanation
Source Link
seshoumara
  • 3.8k
  • 1
  • 14
  • 31

Bash + coreutils, 16 bytes

xargs|tr \ +|bc 
xargs|tr \ +|bc 

Try it online!

There are two spaces after the \. Should workThis works for negative numbers as well.

Explanation:

xargs # known trick to turn newlines into spaces |tr \ + # turn spaces into '+'s |bc # calculates the sum 

Bash + coreutils, 16 bytes

xargs|tr \ +|bc 

There are two spaces after \. Should work for negative numbers as well.

Bash + coreutils, 16 bytes

xargs|tr \ +|bc 

Try it online!

There are two spaces after the \. This works for negative numbers as well.

Explanation:

xargs # known trick to turn newlines into spaces |tr \ + # turn spaces into '+'s |bc # calculates the sum 
Source Link
seshoumara
  • 3.8k
  • 1
  • 14
  • 31

Bash + coreutils, 16 bytes

xargs|tr \ +|bc 

There are two spaces after \. Should work for negative numbers as well.