Adding up the digits and the digits reversed

Given a number > 0, output the sum with all digits (1 .. n) concatenated and reversed and add them up. For example, with n = 6:

The numbers 1 to 6 concatenated:

``````123456
``````

Reversed:

``````654321
``````

Adding them up together will result in: 777777. Another example is n = 11:

``````1 2 3 4 5 6 7 8 9 10 11 > 1234567891011
``````

and

``````11 10 9 8 7 6 5 4 3 2 1 > 1110987654321
``````

Adding them up together will result in `2345555545332`. This is also known as A078262.

Shortest code wins!

-
Related. – Zgarb Feb 22 at 21:21
Is there a bound to `n`, or do we have to support arbitrarily large integers? – LegionMammal978 Feb 22 at 22:16
I think the default is "bounded by `max(256,yourlanguagesdefaultintegertypelimit)`". But it should be specified. – CalculatorFeline Feb 22 at 22:20
@LegionMammal978 As high as your language supports. – Lamaro Feb 22 at 22:43
Important test case: `10`, which should give `23333333231`. – Adnan Feb 22 at 23:04

05AB1E, 7 bytes

``````LDRJsJ+
``````

Try it online.

Explanation

``````LDRJsJ+

L        range from 1 .. input
D       duplicate
R      reverse
JsJ   convert both arrays to strings
+  add (coerces both strings to ints)
``````
-
I feel very confused by the design choice that lead to `+` on lists doing a nested addition, while for strings it converts to ints and then adds. But I guess it worked out here! :P – FryAmTheEggman Feb 22 at 21:35
@FryAmTheEggman I'm going to remove nested addition though. It has never been useful since the moment I've implemented it... – Adnan Feb 22 at 21:41
Sheesh, I leave PPCG for two hours and you rename yourself Aqua Tart while I'm gone... Oh, the life of a PPCG user. – ETHproductions Feb 22 at 23:55

CJam, 15 14 bytes

Thanks to Martin for shaving a byte!

``````ri,:)_W%si\si+
``````

Try it online!

-
1 byte less if you flip the string instead of the numeric array: `ri,:)s_W%i\i+` – Luis Mendo Feb 23 at 1:23
@LuisMendo thanks! – GamrCorps Feb 23 at 3:28
Sorry, I think my version doesn't work for `10` – Luis Mendo Feb 23 at 10:55
This code is secretly happy. `:)` – Cyoce Feb 24 at 0:08

Jelly, 9 bytes

``````R,U\$DF€ḌS
``````

-
Is it me or do I see that code secretly stealing some U\$D? – gcampbell May 21 at 8:20
@gcampbell just u – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ May 21 at 12:20

Pyth, 12 10 bytes

``````ssMjLk_BSQ
``````

Thanks to @FryAmTheEggman for 2 bytes!

`Q` is the input, `S` turns it into `[1, 2, ..., input()]`, `_B` bifurcates it over `_` (reverse) to create `[rng, rev(rng)]`, `jLk` maps it over `join` by `k` (which is the "empty string" variable), `sM` maps `int` over this resulting array, and `s` finally calculates the sum.

-

JavaScript (ES6), 7067 64 bytes

``````a=>(z=[...Array(a)].map((b,c)=>c+1)).join``- -z.reverse().join``
``````

Fixed to meet requirement, as old code was made under misunderstanding of the input.

-
@TimmyD Added an explanation. – Mwr247 Feb 22 at 21:52
@TimmyD OH! >_< My misunderstanding of the challenge is how... Yeah, I'll have to fix this. – Mwr247 Feb 22 at 21:55
@TimmyD Took me long enough to get back online. It's fixed now, and thanks for catching that. – Mwr247 Feb 23 at 16:53
As noted for another answer, this only works if the parameter a is between 1 and 12, that's really too little – edc65 Feb 23 at 20:26
@edc65 Per OP's comment, that's big enough. – Mwr247 Feb 23 at 20:29

Python 3, 74

Saved 6 bytes thanks to DSM.

Nothing too exciting, join the ranges and then convert to ints and add them.

``````lambda x:sum(int(''.join(list(map(str,range(1,x+1)))[::i]))for i in(1,-1))
``````
-

Retina, 71

Because its blatantly the wrong tool for the job.

``````.+
\$*a:\$&\$*
+`^(a+)a\b(.*)\b1(1+)\$
\$1 \$& \$3
?(\w)+ ?
\$#1
\d+:?
\$&\$*c
c
``````

Try it online.

Works for inputs up to 6, but the online interpreter times out after that.

-
You can shorten it to 74 by removing the last line and changing `(c)+` to `c`. – daavko Feb 22 at 22:52
@daavko yes, of course, thanks! – Digital Trauma Feb 22 at 22:59
Also, `\$&\$*c` -> `\$*c` and `\d+:?` -> `\d+` and it's 70. And for some reason it keeps working... – daavko Feb 22 at 23:03

Jolf, 9 bytes

Try it here! Replace `►` with `\x10`.

``````+P►γzjP_γ
zj    range 1...j
γ      γ = ^
►        ^ .join("")
P         as a number
+     P_γ  and γ reversed
``````

I may be able to golf it by moving around the type casting.

-
You beat pyth and doorknob! – Cyoce Feb 26 at 0:05
@Cyoce so I did O_O – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 26 at 0:05

JavaScript (ES6), 67 66 bytes

``````n=>(a=[...Array(n+1).keys()].slice(1)).join``- -a.reverse().join``
``````

Yes, that's a space. Ugh. At least @Downgoat helped me save a byte.

-
You can remove the first `+` and make the `+ +` -> `- -` to save a byte – Downgoat Feb 23 at 1:07
n=>(a=[...Array(n)].map(_=>n--)).join`- -a.reverse().join` – edc65 Feb 23 at 9:07
Note: using simple js arithmetic this is limited to values 1 .. 12 – edc65 Feb 23 at 9:08

Seriously, 12 bytes

``````,R;Rεj≈@εj≈+
``````

Try it online!

Explanation:

``````,R;Rεj≈@εj≈+
,R;           push two copies of range(1, input()+1)
R          reverse one copy
εj≈@εj≈   concatenate both and cast both to ints
``````
-

PowerShell, 35 bytes

``````param(\$a)+-join(1..\$a)+-join(\$a..1)
``````

Converts the input to ranges with `..`, then `-join`s them together, and adds 'em up.

Will work for input numbers up to `138`, while `139` will give `Infinity`, and `140` and above will barf out an awesomely verbose casting error:

``````Cannot convert value "12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413
5136137138139140" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
``````
-

Pyth - 8 bytes

``````siRT_BSQ
``````
-
I think this doesn't work for `10` or `11` – Luis Mendo Feb 23 at 9:59

JavaScript (ES6), 99

This adds digit by digit, so it can handle numbers well above the 53 bits of precision of javascript

``````n=>eval("for(a=b=c=r='';n;a+=n--)b=n+b;for(i=a.length;i--;r=c%10+r)c=(c>9)-(-a[i]-b[i]);c>9?1+r:r")
``````

Test

``````f=n=>eval("for(a=b=c=r='';n;a+=n--)b=n+b;for(i=a.length;i--;r=c%10+r)c=(c>9)-(-a[i]-b[i]);c>9?1+r:r")

// Less golfed
U=n=>{
for(a=b=c=r=''; n; --n)
b=n+b, a+=n;
for(i=a.length; i--; r = c%10+r)
c=(c>9)-(-a[i]-b[i]);
return c>9? 1+r : r;
}

function test() {
var n=+I.value
R.textContent=f(n)
}

test()``````
``N: <input id=I value=11 oninput="test()"> -> <span id=R></span>``

-
Doesn't seem to work for 9. Also, why not initialise `c` with the other variables? – Neil Feb 22 at 22:54
You have my upvote. – Neil Feb 23 at 9:24

Brachylog, 24 bytes

``````:1fLrcC,Lc+C=.,{,.:1re?}
``````
-

MATL, 13 bytes

``````:tP2:"wVXvU]+
``````

EDIT (May 20, 2016) The code in the link uses `Xz` instead of `Xv`, owing to recent changes in the language.

Try it online!

``````:                % range [1,2,...,n], where n is input
tP              % duplicate and flip
2:"     ]     % do this twice
w          % swap
V         % convert array of numbers to string with numbers and spaces
Xv       % remove spaces
U      % convert to number
+    % add the two numbers
``````
-
Doesn't work for 11 or 10. (Hint: reverse range before converting to string.) – Mama Fun Roll Feb 23 at 3:32
@ӍѲꝆΛҐӍΛПҒЦꝆ Thanks! Corrected – Luis Mendo Feb 23 at 9:57
Great! Have an upvote. – Mama Fun Roll Feb 24 at 2:00

Bash + coreutils, 39

``````eval echo {1..\$1} + {\$1..1}|tr -d \ |bc
``````

Or:

``````bc<<<`eval printf %s {1..\$1} + {\$1..1}`
``````

Ideone.

-

Perl 6, 25 bytes

``````{([~] @_=1..\$^n)+[R~] @_}
``````
``````{
(
[~]           # reduce with the string concatenation infix op:
@_ = 1 .. \$^n # the range 1 to input ( also stored in @_ )
)
[R~] @_         # @_ reduced in reverse
}
``````

Usage:

``````for 6, 11, 12 -> \$n {
say {([~] @_=1..\$^n)+[R~] @_}( \$n )
}
``````
``````777777
2345555545332
244567776755433
``````
-
I think you can do with `\$n` instead of `\$^n` – andlrc Feb 22 at 22:56
@dev-null Not if I want it to be an input to the block. the `-> \$n {` is a different one to `\$^n`. – Brad Gilbert b2gills Feb 22 at 22:58

R, 3460 64 bytes

``````f=pryr::f;g=f(as.numeric(paste(x,collapse='')));f(g(1:n)+g(n:1))
``````

Assumes `pryr` package is installed. this gives `f` as a shorthand for creating functions.

Edit added 26 bytes but returns a function that works, not something entirely wrong.

Edit added another 4 bytes to handle cases above n=10 where strtoi (previously used) was returning `NA`

-

Lua, 57

``````a=''b=''for i=1,...do a=a..i b=b.. ...-i+1 end return a+b
``````
-

Lua, 53 Bytes

This program takes `n` as a command-line argument.

``````s=""r=s for i=1,arg[1]do r,s=i..r,s..i end print(s+r)
``````

I assumed that outputing a number with a decimal part of 0 was okay (in the form `777777.0` because this is the default way to output a number in lua (there's no distinction between integer and float)

-
Its not the string itself that is reversed, but the digits. Your code fails on n >= 10. – Moop Feb 23 at 7:47
@Moop Corrected at the price of 1 byte ^^'. Thanks for the comment ^^' – Katenkyo Feb 23 at 8:00
You can save 3 more using ... instead of arg[1] nice work on the reverse concat for r, didn't think of that in my answer. +1 – Moop Feb 23 at 8:03
@Moop I saw your post, nice use of it, I didn't even know you could use `...` like that! I'll keep it this way for the moment, because I can't use anything else than the online compiler and it can't handle that(I'd like to test it and play with it a little bit before putting it in a answer :)) – Katenkyo Feb 23 at 8:07

Perl 5, 37 bytes

25 bytes, plus 1 for `-p` and 11 for `-MList::Gen`

``````\$_=<[.]1..\$_>+<[R.]1..\$_>
``````

Previous solution, 40 bytes: 39, plus one for `-p`

``````@a=reverse@_=1..\$_;\$"=\$\;\$_="@a"+"@_"
``````
-

Perl, 36 bytes

Includes +1 for `-p`

Run with on STDIN

``````perl -p reverse.pl <<< 6
``````

`reverse.pl`

``````\$_=eval join"",map{abs||"+"}-\$_..\$_
``````
-

Dyalog APL, 17 bytes

``````+/⍎¨∊¨⍕¨¨x(⌽x←⍳⎕)
``````

`⎕` prompt for input
`⍳`' enumerate until input
`x←` store list in x
`⌽` reverse x
`x(``)` prepend reversed list with original list
`⍕¨¨` convert each number of each list into character string
`∊¨` make each list of character strings into single character strings
`⍎¨` convert each character string into a number
`+/` sum the two numbers.

-

Mathematica, 64 bytes

``````Plus@@FromDigits/@#&[""<>ToString/@#&/@{#,Reverse@#}&[Range@#]]&
``````
-

Retina, 80 bytes (ISO 8859-1 encoding)

``````'+
\$0¶\$0
+`^(('+)')
\$2 \$1
+`('('+))\$
\$1 \$2
(')+( |\$)?
\$#1
(\d+)¶(\d+)
\$1\$*'\$2\$*'
``````

IO is in unary with `'` as the counting character. In theory supports any integer you throw at it, in practice...online interpreter refuses to process anything larger than 6 (unary `''''''`).

-

𝔼𝕊𝕄𝕚𝕟, 12 chars / 15 bytes

``````⨭⟮⩤⁽1ï⟯⨝,Ⅰᴚ⨝
``````

Try it here (Firefox only).

Meh.

Explanation

Takes a range `[1,input]`, joins it; takes that same range, reverses it, then joins it; the sum of both ranges is the result.

-

Ruby, 40 characters

``````->n{eval (l=[*1..n])*''+?++l.reverse*''}
``````

Sample run:

``````irb(main):001:0> ->n{eval (l=[*1..n])*''+?++l.reverse*''}[11]
=> 2345555545332

irb(main):002:0> ->n{eval (l=[*1..n])*''+?++l.reverse*''}[6]
=> 777777
``````
-

C#, 126 bytes

``````using System.Linq;a=>{var b=Enumerable.Range(1,a);return long.Parse(string.Concat(b))+long.Parse(string.Concat(b.Reverse()));}
``````

Could possibly be golfed further. Not really sure.

-

Groovy, 42 39 characters

``````{[1..it,it..1]*.join()*.toLong().sum()}
``````

Sample run:

``````groovy:000> ({[1..it,it..1]*.join()*.toLong().sum()})(11)
===> 2345555545332

groovy:000> ({[1..it,it..1]*.join()*.toLong().sum()})(6)
===> 777777
``````
-

Groovy, 112 characters

``````def r(n){if(n==1){return n;};return n+''+r(n-1)};n=6;s=r(args[0].toLong());print s.toLong()+s.reverse().toLong()
``````

run with:

``````groovy filename.groovy *input*
``````
-

protected by Community♦Mar 16 at 20:27

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).