Assume that there is a number a. In every conversion of that number, the number can either convert itself to its value plus the value of one of its digits, or convert itself to its value minus the value of one of its digits.

In this situation, find the minimum number of conversions one has to make in order to get to the number b. If b cannot be reached, output -1.


Input one line containing the integers a and b (where 1 <= a, and b <= 10^6).


Output a line containing one integer, which represents the minimum amount that one has to convert the number.

Example input and output (s)

Input:  1 10
Output: 5


-> 1+1=2
-> 2+2=4
-> 4+4=8
-> 8+8=16
-> 16-6=10
=> 10

The shortest program wins, as this is a code golf question.

  • 8
    \$\begingroup\$ You should make sure to specify a winning condition. This seems like it would fit under code-golf but it is unclear. \$\endgroup\$ – Theo Jun 21 at 15:05
  • 3
    \$\begingroup\$ Nice challenge! It would probably be good to also provide a test case where b cannot be reached, and the function/program should return -1. \$\endgroup\$ – ArBo Jun 21 at 15:34
  • 12
    \$\begingroup\$ I would suggest guaranteeing that a solution can always be reached. \$\endgroup\$ – Shaggy Jun 21 at 15:35
  • 2
    \$\begingroup\$ Or allow any behaviour, other than outputting a non-negative number, if it’s not possible to reach b \$\endgroup\$ – Luis Mendo Jun 21 at 16:56
  • 5
    \$\begingroup\$ Also, this needs a few test cases, including one with output 0 \$\endgroup\$ – Luis Mendo Jun 21 at 16:57

JavaScript (ES6), 98 bytes

Takes input as (a)(b). Can be very slow if there's no solution, but it should eventually return \$-1\$ (at least in theory).


Try it online!

  • \$\begingroup\$ Can this handle cases where a>b? I'm not sure if those cases are allowed by the author of the question. \$\endgroup\$ – fəˈnɛtɪk Jun 21 at 17:09
  • \$\begingroup\$ @fəˈnɛtɪk Yes, I've added a test case. \$\endgroup\$ – Arnauld Jun 21 at 17:13
  • \$\begingroup\$ Thanks. I just wasn't sure because the tests I tried caused it to timeout. They were for cases where it should return -1 \$\endgroup\$ – fəˈnɛtɪk Jun 21 at 17:14

05AB1E, 38 37 bytes


Can definitely be golfed a bit more..

Thanks to @tsh for the condition of the first if-statement.

Try it online or verify a few more test cases.


3Ý             # Push the list [0,1,2,3]
  o            # For each value, take 2 to the power that value: [1,2,4,8]
   *           # Multiply each by the first (implicit) input
    Êß         # Check that the second (implicit) input is NOT in this list
8L             # Push the list [1,2,3,4,5,6,7,8]
  Iå           # Check that the second input is in this list
*i             # If both are truthy:
  ®            #  Push -1
 ë             # Else:
  ¹¸           #  Push the first input again, and wrap it into a list
    [          #  Start an infinite loop:
     D         #  Duplicate the list at the top of the stack
      Iå       #  If the second input is in this list:
        #      #   Stop the infinite loop
      ¼        #  Increase the counter variable by 1
      v        #  Loop over each number `y` in the list:
       y©      #   Store the current number `y` in variable `®` (without popping)
         v     #   Inner loop over each digit `y2` of `y`
          ®y+  #    Add digit `y2` to integer `®`
          ®y-  #    Subtract digit `y2` from integer `®`
      }}       #  After the nested loop:
        )      #  Wrap all values on the stack into a list for the next iteration
    }¾         # After the infinite loop: push the counter variable
               # (and output the top of the stack implicitly as result)

Jelly, 33 29 bytes


Try it online!

A full program that takes [[a]] as the left argument and b as the right argument.

More efficient version (36 bytes)


Python 2, 104 99 96 93 95 bytes

f=lambda a,b,i=0:i*(b in a)-(0<b<9<i)or f({x+int(c+d)for x in a for d in`x`for c in' -'},b,i+1)

Try it online!

This function takes a as a list (or set, or any other collection really), which is not ideal, but the Jelly answer does something similar it seems. My original approach with varargs couldn't be used because I needed the i parameter, with a default value, to return -1 if no answer can be found.

@tsh's prerequisites for there not being an answer are partially used. However, instead of the expensive and highly unpractical (for golfing) second part of that condition, we simply let the recursion run for a little while to see if an answer is found anyway.


f=lambda a,b,                       # a and b are as defined in the
         i=0:                       #  challenge; i is a counter
i*(b in a)                          # Return the counter if b is found
-(0<b<9<i)                          # This is the only code needed for the 
                                    #  existence problem
or f(                               # Recursively call the function
 {x+int(c+d)                        # All possible numbers in the next step
  for x in a                        # All numbers in this step
  for d in`x`                       # All digits of those numbers
  for c in' -'},                    # Either positive or negative (making
                                    #  good use of the fact that int()
                                    #  ignores leading whitespace)
 b,i+1)                             # Increase the counter

C# (Visual C# Interactive Compiler), 217 bytes

Correctly returns -1 now if b can't be reached, thanks to @tsh for the formula

(a,b)=>{var l=new List<int>(){a};int r=-1,z;if(!(b<9&!(b==a|b==2*a|b==4*a|b==8*a)))for(r=0;!l.Any(x=>x==b);r++)l.ToList().ForEach(x=>(x+"").ToList().ForEach(y=>{z=y-'0';l.Remove(x);l.Add(x+z);l.Add(x-z);}));return r;}

Try it online!

  • \$\begingroup\$ Does this just check every possible branch? \$\endgroup\$ – fəˈnɛtɪk Jun 21 at 16:07
  • 2
    \$\begingroup\$ This doesn't return if there is no valid path to the number. If you put a=1 and b=3 it runs forever. \$\endgroup\$ – fəˈnɛtɪk Jun 21 at 16:30
  • \$\begingroup\$ OP hasnt even specified what to return in such scenario \$\endgroup\$ – Innat3 Jun 21 at 16:55
  • 1
    \$\begingroup\$ "If b cannot be reached, output -1." \$\endgroup\$ – fəˈnɛtɪk Jun 21 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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