26
\$\begingroup\$

This challenge is based on this Stackoverflow question.

With a positive number as input, output it as the sum of each digit multiplied by its power-of-10 representation.

Input

A number, as an integer, a string or a list of digits/characters.

  • The number will be strictly positive.
  • If you accept the number as a string or list, it will not start with a 0.

Output

A string representing a sum of each relevant base-10 digits, each multiplied by its respective base-10 power. A sum is represented as a + b. You may use up to one space around each side of the + sign if you want. The operands are listed in descending order.

  • 0 can never be a valid operand.
  • The + sign (surrounded or not by spaces) may not be the leading or trailing part.

Examples

Input       Output
12          10 + 2
         or 10+2
         or 10 +2
         or 10+ 2
9           9
123         100 + 20 + 3
10          10
101         100 + 1

Invalid outputs

2           1 + 1
10          10 + 0
1           0 + 1
12          + 10 + 2
12          10 + 2 +
12          2 + 10

This is code-golf so the shortest code in bytes wins!

\$\endgroup\$
13
  • \$\begingroup\$ Sandbox \$\endgroup\$ Sep 9, 2018 at 8:13
  • \$\begingroup\$ Related \$\endgroup\$ Sep 9, 2018 at 12:32
  • \$\begingroup\$ Can we output the sum in reverse? Ex. 123 = 3+20+100 \$\endgroup\$
    – Quintec
    Sep 9, 2018 at 15:32
  • 1
    \$\begingroup\$ are leading and trailing spaces allowed? \$\endgroup\$
    – ngn
    Sep 9, 2018 at 21:10
  • 2
    \$\begingroup\$ What is the expected output for input 0? (If 0 is an invalid input in the first place, then it should be removed from the invalid output examples IMO) \$\endgroup\$
    – Pedro A
    Sep 10, 2018 at 11:55

42 Answers 42

1
2
2
\$\begingroup\$

MathGolf, 12 11 10 bytes

hrzúm*ç'+u

Try it online!

Explanation

The first command is not needed as input can be given as a list of digits.

(▒           Convert to a list of digits)
 h           Get length of input list without popping
  r          Push range(a)
   z         Reverse sort
    ú        Map i -> 10**i for each element in list
     m*      Element-wise multiplication
       ç     Filter faulty items in list
        '+   Push "+"
          u  Join with separator

I might add a pairwise multiplication operator that is one byte, but that's not currently part of the language. Then I could remove one byte from this solution.

\$\endgroup\$
2
\$\begingroup\$

Vyxal, 8 bytes

ẏṘ↵*ꜝ\+j

Takes input as a list of digits.

Try it online, or verify all test cases.

Explanation:

   *       # Multiply each digit in the input by the corresponding value in:
ẏ          # the range from 0 to the length of the input
 Ṙ         # reversed
  ↵        # with each value mapped to 10^n.
    ꜝ      # Remove falsey values.
     j     # Join on
       \+  # "+"
\$\endgroup\$
1
\$\begingroup\$

Wolfram Language (Mathematica), 58 bytes

StringRiffle[ToString/@(NumberExpand[#]/.(0->Nothing)),"+"]&

In Use:

In[101]:= StringRiffle[ToString /@ (NumberExpand[#] /. (0 -> Nothing)), "+"] &[101]
Out[101]= "100+1"
\$\endgroup\$
1
\$\begingroup\$

BASH, 86 83 bytes

Try it online!

for((t=$1;++m<${#1};t=10#$g)){
g=${t#?}
b+=${t/$g}${g//?/0}+;}
a=$b$t
echo ${a//+0}
\$\endgroup\$
1
\$\begingroup\$

Pip, 21 bytes

W+:axPB['+POa0Ma];@>x

Takes input as a command-line argument. Try it online!

Explanation

Partially inspired by nimi's Haskell answer.

                       x is empty string; a is 1st cmdline arg (implicit)
W                      While loop
 +:a                    Loop condition: a, after unary + is applied in-place
                         Unary + adds 0 to a number, with the side effect of converting it to
                         standard numerical form; in this case, that means eliminating leading zeros
                        Inside the loop, we know that a is nonzero and has no leading zeros
       [        ]       Construct a list containing the following items:
        '+               A + character
          POa            Pop the first character from a (leaving a one character shorter)
             0Ma         Map 0 to a, giving a list of 0's with the same length as a
                        E.g. if a was 123, the list is ["+" 1 [0 0]] and a becomes 23
    xPB                 Push this list to the back of x
                        Since x is a string, PB will cast the list to a string and append it to x
                        The default list -> string format is to concatenate all the items, so in
                        the above example, x will have "+100" appended
                 ;     Required for parsing
                  @>x  Take all but the first character of x and autoprint it

Here's a less creative map-and-filter approach, also 21 bytes:

_FI_*t**BMZaRV,#aJ:'+

Try it online!

I tried a few ways to golf this, but ran into parsing problems that forced me back up to 21. Quite possibly there's a shorter way to do it.

\$\endgroup\$
1
\$\begingroup\$

Python 3, 114 bytes

s,n=[],input()
[s.append(("+"+n[-i-1]+"0"*i)*(int(n[-i-1])>0))for i in range(len(n))]
print("".join(s[::-1])[1:])

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Why do you use a list comprehension to simulate a for loop that fills a list? Anyhow, 66 bytes. \$\endgroup\$ Sep 14, 2018 at 2:16
  • \$\begingroup\$ I think I planned on having it be on one line but then I changed my mind and didn't reflect that back into the design; now that you say this, I think I will go back and make this cleaner. \$\endgroup\$
    – Josh B.
    Sep 14, 2018 at 2:32
1
\$\begingroup\$

brainfuck, 116 bytes

--->-[<+>-----]>,[>,]<[<]>[<<[->+>-<<]>>[[>]>[<<[<]>-----.+++++[>]]<<[<]>[->+<<+>]>.,>[[-<+>]<[<]<.>>[>]>],+<<[<]]>]

Try it online!

Explanation:

--->-[<+>-----]     Push 48
Tape: 48 0'
>,[>,]<[<]          Get all inputted digits
Tape: 48 0' digits
>[                  Loop over each digit
  Tape: 48 0 d' igits
  <<[->+>-<<]       Subtract 48 from the digit       
  Tape: 0' 48 d-48 igits
  >>[               If the digit is not a zero
     [>]>[          Check if the flag is set
        [<]>-----.  Subtract 5 from the 48 to print a plus
        +++++[>]    Restore the 48
     ]
     <[->+<<+>]     Restore the 48 and the first digit
     Tape: 48 0' d igits
     >.,            Print and remove the first digit
     Tape: 48 0 0' igits
     >[             For each of the remaining digits
        [-<+>]      Move it over one
        <[<]<.      Print a zero
        >>[>]>      Move to the next digit
     ]
     Tape: 48 0 digits? 0 0'
     ,+<<[<]        Set the plus flag
     Tape: 48 0' digits? 0 1
  ]
  Tape: 48 0' digits?
>]
\$\endgroup\$
1
\$\begingroup\$

PHP, 89 bytes

<?for($i=0;$i<$l=strlen($a=$argv[1]);$i++)echo$a[$i]?($i?"+":"").$a[$i]*10**($l-$i-1):"";

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Ruby, 55 bytes

->n{w=-1;(n.digits.map{|x|x*=10**w+=1}-[0]).reverse*?+}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

MBASIC, 131 bytes

1 INPUT N$:N=VAL(N$):FOR P=LEN(N$)-1 TO 0 STEP -1:T=10^P:X=INT(N/T):G=X*T
2 IF G>0 THEN PRINT G;:N=N-G:IF N>0 THEN PRINT"+";
3 NEXT P

Input a number as a string, allowing us to walk it's length, subtracting power of 10 multiples as we go.

? 12
10 + 2

? 9
9

? 123
100 + 20 + 3

? 10
10

? 101
100 + 1
\$\endgroup\$
1
\$\begingroup\$

Thunno 2, 9 bytes

Żre×0o'+j

Try it online!

Note: 0o could also be æ; or Dị.

Explanation

Żre×0o'+j  '# Implicit input
Żr          # Push (length..0]
  e         # Ten power of each
   ×        # Multiply with input
    0o      # Remove zeros
    æ;      # OR truthy items only
    Dị      # OR filter by itself
      '+j  '# Join by "+"
            # Implicit output
\$\endgroup\$
1
\$\begingroup\$

Ruby -pl, 47 bytes

gsub(/.(?=.)/){$&+?0*$'.size+?+}
gsub /\+0+/,''

Attempt This Online!

\$\endgroup\$
1
2

Your Answer

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

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