'Find the largest Pair in an integer
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 1:[1]
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 ...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | derpirscher |