I’m playing around with numbers, and I’m looking to write a small program that will return the largest double-digit of an integer that’s passed in for example:
I pass in 2215487
it should return 87
I pass in 98765499
It should return 99
I’ve tried looking at Math.Max, but I don’t believe that’s what I’m looking for unless I have overlooked it
>Solution :
You can divide by 10 each time and then compare the remainder of dividing the remaining number by 100. For example:
int v = 98765499;
int m = 0;
v = Math.Abs(v); // negate negative numbers so that we can process these too
while (v >= 10) // if you want to accept single digits change this to v > 0
{
m = Math.Max(m, v % 100);
v /= 10;
}
Console.WriteLine(m);
We use v >= 10 because we don’t want to consider single-digit numbers.
v % 100 uses the remainder operator to give us the value left over when we divide by 100.
v /= 10 divides v by 10 and stores the result in v.
I’ve used Math.Abs( ) to make this work with negative numbers too, though you can take this line out if you only care about positive numbers.
At the end, m will either hold 0 (for single digit numbers or zero) or the highest two-digit value.
Example execution flow:
| Initial V | V % 100 | New V |
|---|---|---|
| 98765499 | 99 | 9876549 |
| 9876549 | 49 | 987654 |
| 987654 | 54 | 98765 |
| 98765 | 65 | 9876 |
| 9876 | 76 | 987 |
| 987 | 87 | 98 |
| 98 | 98 | 9 |
Highest v % 100 is 99.