about | help | code help+videos | done | prefs |
dec16_2019_HL_stepsNeeded
Write a method that returns the minimum number of "steps" required to make the two non-negative integer input parameters "match". Each "step" allows you to change one digit of one of the numbers up or down one digit. The numbers "match" when they are the same number. Note that you are not ADDING or SUBTRACTING from a digit, you are just changing it to an adjacent digit. For example, the digit 6 could be changed into 7 or 5. But the digit 9 can only be changed to an 8 and the digit 0 can only be changed to a 1. So you can't add one to 9 and get 10. You may assume as a precondition that the two input parameters have the same number of digits. Here is an example: if the two input parameters are 41 and 53, return a 3 because it takes a minimum of 3 "steps" to make the numbers match. One possible sequence of "steps" is to only change the first number by changing the 4 to a 5, then change the 1 to a 2, and finally change the 2 to a 3. So three steps works and it is the minimum number of steps! Look at the test data for further examples. This sounds complicated, but it is not nearly as complicated as it sounds. You can do it recursively, but that is not required. Without recursion I wrote this in 6 lines of code (not counting braces). With recursion, I solved this in one line! dec16_2019_HL_stepsNeeded(0, 0) → 0 dec16_2019_HL_stepsNeeded(123, 987) → 18 dec16_2019_HL_stepsNeeded(43, 91) → 7 ...Save, Compile, Run (ctrl-enter) |
Progress graphs:
Your progress graph for this problem
Random user progress graph for this problem
Random Epic Progress Graph
Difficulty: 290
Copyright Nick Parlante 2017 - privacy