# Answer to Question #74965 in C++ for Crystal

Question #74965

Write a function, smallest, which given positive integer n and a positive integer key returns the smallest digit in n greater than key. Your function should also work if there is no digit in n smaller than key.

Expert's answer

#include <iostream>

using namespace std;

int smallest(int n, int k)

{

int smallestDigit = 10;

do

{

int residue = n % 10;

if (residue > k && residue < smallestDigit)

smallestDigit = residue;

} while (n = n / 10);

if (smallestDigit == 10)

smallestDigit = -1;

return smallestDigit;

}

int main()

{

cout << smallest(567, 4) << endl;

}

using namespace std;

int smallest(int n, int k)

{

int smallestDigit = 10;

do

{

int residue = n % 10;

if (residue > k && residue < smallestDigit)

smallestDigit = residue;

} while (n = n / 10);

if (smallestDigit == 10)

smallestDigit = -1;

return smallestDigit;

}

int main()

{

cout << smallest(567, 4) << endl;

}

Need a fast expert's response?

Submit orderand get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

## Comments

## Leave a comment