Problem Statement
You are given an integer n
. Return the largest digit present in the number.
Examples
Example 1:
Input: n = 17
Output: 7
Explanation: The digit 7 is the largest digit, greater than 1.
Example 2:
Input: n = 66
Output: 6
Explanation: Both the digits are same.
Example 3:
Input: n = 7
Output: 7
Explanation: Since there is a single digit, and a single digit
itself is the largest.
Approaches
1️⃣ Modulus & Division
Intuition:
Given a number, all the digits can be extracted from the back (right) successively and the maximum of all the digits can be found by comparing every digit.
Approach:
- Initialize a variable largest digit with zero that will store the largest digit in the given number.
- The last digit of the original number can be found by using the modulus operator (used to find the remainder for any division) with the number 10.
- Iterate on the original number till there are digits left. In every iteration, extract the last (rightmost) digit and check if it is greater than the largest digit. If found greater, update the largest digit with the current digit.
- Once the iterations are over, the largest digit in the given number is returned as answer.
Code:
#include <iostream>
int findLargestDigit(int n) {
int maxDigit = 0; // Initialize the max digit to 0
while (n > 0) {
int digit = n % 10; // Extract the last digit
if (digit > maxDigit) {
maxDigit = digit; // Update max digit if the current digit is larger
}
n = n / 10; // Remove the last digit
}
return maxDigit;
}
int main() {
int n;
std::cout << "Enter a number: ";
std::cin >> n;
int result = findLargestDigit(n);
std::cout << "The largest digit in the number is: " << result << std::endl;
return 0;
}
Complexity Analysis:
- Time Complexity:
O(log10(N))
– In every iteration,N
is divided by 10 (equivalent to the number of digits inN
.) - Space Complexity:
O(1)
– Using a couple of variables i.e., constant space.