### Question: Get the difference for the largest and smallest number in a positive integer

Create a function to get the difference for the largest and smallest number in a positive number. For example integer 98721, the difference is 9 - 1, so the function would return 8. I have written this to solve it, but wonder if there is a better way of solving this problem. No array anyway, this question doesn't allow me to use array, only loop, if else and function.

 ``123456789101112131415161718192021222324252627282930313233343536`` `````` int differenceMaxMin (int); int main() { int n; cout << "Enter a positive integer: " cin >> n; cout << "The differences of the largest and smallest number is: " << int differenceMaxMin (n) << endl; } int differenceMaxMin (int n) { int lastD, nextD, max, min; lastD = n % 10; max = lastD; n = n / 10; nextD = n % 10; min = nextD; while (n > 0) { if (max < nextD) max = nextD; else if (min > nextD) min = nextD; n = n / 10; nextD = n % 10; } return (max - min) } ``````
Last edited on
Line 10 is wrong. Don't specify the return type of a function when you use it. Only when you define the function.

You are unfortunately restricted in what you're permitted to use; making use of C++, you could do something like this:

 ``12345`` `````` string n; cout << "Enter a positive integer: " cin >> n; cout << '\n' << *std::max_element(n.begin(), n.end()) - *std::min_element(n.begin(), n.end());``````

Under the restrictions you have, looping through the value to find the max and min is about all you can do.
Last edited on
@Repeater, oops should be differenceMaxMin (n) right?
 ``12345678910111213141516`` ``````#include unsigned int max_digit( unsigned int n ) { if( n < 10 ) return n ; else return std::max( n%10, max_digit(n/10) ) ; } unsigned int min_digit( unsigned int n ) { if( n < 10 ) return n ; else return std::min( n%10, min_digit(n/10) ) ; } unsigned int diff_max_min_digits( unsigned int n ) { return max_digit(n) - min_digit(n) ; }``````
Topic archived. No new replies allowed.