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
CodePudding user response:
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 digit initial values for V 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 (e.g. an initial value of v = 5).
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.
CodePudding user response:
A very simple solution would be as follows:
var thenumber = 987654990;
var s = thenumber.ToString();
var max = 0;
for (var i = 0; i < s.Length-1; i ) {
int d1 = (int)(s[i] - '0');
int d2 = (int)(s[i 1] - '0');
max = Math.Max(max, 10*d1 d2);
}
Console.WriteLine(max);
Ie, just iterate over the number and calculate the "pair" at the current position (consisting of the current digit d1
and the next one d2
) if the pair is greater than the current max, make it the new max ...