Question

A 4-number bicycle combination lock has four rings with numbers 0 through 9, as in the...

A 4-number bicycle combination lock has four rings with numbers 0 through 9, as in the above picture.

Write a method that accepts two ints: 1) starting: the current numbers of the lock (assume you will always get a 4-digit int) and 2) target: the combination required to unlock (assume you will always get a 4-digit int). Return the minimum number of "twists" to unlock the lock.
Twists can either be "up" or "down." A twist up increases the number value of a ring by 1, and a twist down decreases it by 1. For example, if the current number shown is 1729 and the required combination to unlock is 5714, your method should return 10 (4 twist ups for ring #1 + 1 twist down for ring #3 + 5 twists down/up for ring #4 = 10 twists total).

Examples:
problem5_getNumTwists(1729, 5714) // returns 10
problem5_getNumTwists(0000, 9999) // returns 4
problem5_getNumTwists(4590, 4590) // returns 0
problem5_getNumTwists(7712, 1729) // returns 8

Homework Answers

Answer #1

Following is the C++ implementation of the given problem

#include<bits/stdc++.h>
using namespace std;

int getNumTwists(int current, int required) {

    int ans = 0;

    while(current != 0 && required != 0) {

        int curr_digit = current % 10;
        current = current / 10;

        int req_digit = required % 10;
        required = required / 10;

        int temp = abs(curr_digit - req_digit);

        ans += (temp > (10 - temp)) ? (10 - temp) : temp;

    }

    return ans;

}

int main() {

    int curr,req;
    cin>>curr>>req;
    cout<<getNumTwists(curr,req)<<endl;

        return 0;
}
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT