Return the Largest Digit in a Number
Pattern: Maths basics
Find the biggest digit of a number by looking at each digit once and keeping the best so far.
The problem
You are given a whole number n that is zero or more and fits in a 32-bit integer. Return its largest decimal digit.
For example, the largest digit of 4721 is 7, and the largest digit of 1000 is 1.
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name largestDigit and the limits above are this guide's own.
Think first
- How do you get one digit of 4721 out as a number you can compare?
- If you look at the digits one at a time, what single value do you need to remember between them?
- What should that value start at, so that the first digit always replaces it?
Hints
Brute force, and why it fails
You could turn the number into text and take the largest character, or put all the digits into a list and sort it. Both work and are fast, since there are at most 10 digits. Sorting does more work than needed, though: you only want the top value, not the whole order. A single pass that keeps the best so far is simpler, and it is the pattern behind every "find the maximum" problem you will meet later.
The key insight
To find the biggest item, you never need to see everything at once. Look at each digit once and keep the best so far. When the digits run out, the best so far is the answer.
Dry run
| n | 4721 |
|---|---|
| largest | 0 |
Start with n = 4721 and largest = 0. The digits are shown left to right.
The plan
largest = 0
while n > 0:
digit = n mod 10
if digit > largest:
largest = digit # a new best
n = n div 10 # drop the last digit
return largest
Complexity
- Time
O(d)- Space
O(1)
d is the number of digits, each looked at once. Only three variables are kept.
Edge cases
n = 0returns 0. The loop does not run, and the starting value 0 is the right answer.- A single digit returns itself.
- 1000 returns 1. The zeros never beat the 1.
- If every digit is the same, such as 333, the answer is that digit.
I've built my logic, show the code
Java
class Solution {
public int largestDigit(int n) {
int largest = 0;
while (n > 0) {
int digit = n % 10;
if (digit > largest) {
largest = digit;
}
n = n / 10;
}
return largest;
}
}C++
class Solution {
public:
int largestDigit(int n) {
int largest = 0;
while (n > 0) {
int digit = n % 10;
if (digit > largest) {
largest = digit;
}
n = n / 10;
}
return largest;
}
};Python
class Solution:
def largestDigit(self, n):
largest = 0
while n > 0:
digit = n % 10
if digit > largest:
largest = digit
n = n // 10
return largestCommon mistakes
- Starting
largestat the first digit and then also testing that digit again (harmless here, but a sign of muddled set-up). - Comparing
ninstead ofdigitwithlargest. - Forgetting to shrink
n, which loops forever.