logo CodeStepByStep logo

largestDigit

Language/Type: C++ recursion return

Write a recursive function named largestDigit that accepts an integer parameter and returns the largest digit value that appears in that integer. Your function should work for both positive and negative numbers. If a number contains only a single digit, that digit's value is by definition the largest. The following table shows several example calls:

Call Returns
largestDigit(14263203) 6
largestDigit(845) 8
largestDigit(52649) 9
largestDigit(3) 3
largestDigit(0) 0
largestDigit(-573026) 7
largestDigit(-2) 2

Constraints: You may not use a string, array, vector, or any data structure (stack, map, set, etc.). Your function must be recursive and not use any loops (for, while, etc.). Your solution should run in no worse than O(N) time, where N is the number of digits in the number.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.