1

After finding the highest digit in a number,how to find the 2nd highest digit in that same number using only loops and if statements?

    public static int maximum(int max){

while(num != 0){
            int rightDigit = num % 10;
            num /= 10;
            if(rightDigit > max)
                rightDigit = max;
        }
        return max;
        }
user2991964
  • 11
  • 1
  • 1
  • 3
  • Only way would to do this in one loop would be to keep a list of all the values, sort them and pull the top two off. – christopher Nov 14 '13 at 12:15
  • So, are you trying to get `7` and `5` from `125673`? Also, are you checking for duplicates? – Mr. Polywhirl Nov 14 '13 at 12:18
  • 1
    your while loop will not be accessed since num = 0. – Sionnach733 Nov 14 '13 at 12:18
  • 1
    @Chris Or just keep a reference to the two highest digits around, then use if blocks to keep them in sync. – Tim Pote Nov 14 '13 at 12:18
  • if the number is 52163429 then highest and second highest are 9 & 6 . if the number is 45886 the highest and second highest should be 8 & 6.Also it should be done using loop and if statements – user2991964 Nov 14 '13 at 12:22
  • Refer [Find Second largest number in array at most n+log₂(n)−2 comparisons](http://stackoverflow.com/questions/9889679/find-second-largest-number-in-array-at-most-nlogn2-comparisons) – Amit Deshpande Nov 14 '13 at 12:25
  • What if the highest number is repeated, like `818`. Is the answer `8` (since `8` is both the highest "twice" so to speak), or `1`? – Willem Van Onsem Jul 20 '18 at 11:44

7 Answers7

3

Use a List to store all digits and sort it, that way you have access to the highest, second highest to lowest digit as you wish. To sort a List use Collections.sort(List list)

LionC
  • 3,106
  • 1
  • 22
  • 31
  • Considering he's dealing with ints (which have a max length of 10), this is by far the easiest solution. – Tim Pote Nov 14 '13 at 12:21
  • This is the most practical, as long as the OP isn't asking for homework. – Ron Nov 14 '13 at 12:21
  • I was thinking to add another solution with a second variable but ended up thinking that for the amount of digits thit would really just end up in hardly readable messy code and this is much cleaner from a design perspective – LionC Nov 14 '13 at 12:22
  • 1
    @Marco, Set implies that there are no duplicates. OP has not specified this. Perhaps a `TreeList` is the correct structure – Ron Nov 14 '13 at 12:23
  • @Marco there are obviously a lot of different Collections to achieve this :) a SearchTree for example – LionC Nov 14 '13 at 12:24
  • @RonE but if we only want the two highest digits i think we don't care if there are more then one of them – Marco Forberg Nov 14 '13 at 12:25
  • @TimPote if the number is 52163429 then highest and second highest are 9 & 6 . if the number is 45886 the highest and second highest should be 8 & 6.Also it should be done using loop and if statements.NO use of LIST or Collections – user2991964 Nov 14 '13 at 12:25
  • 1
    @user2991964 HOMEWORK! – Ron Nov 14 '13 at 12:26
  • this doesn't work if there are duplicate digits in the number, assume a number "54352", with this method, you will be getting 5 as both highest and second highest method, where required answer is 5 and 4. – raviraja Dec 18 '18 at 06:26
0

Is this what you want? first element in array is largest, second element is second largest. Returns -1 if no such element.

public static void main(String[] args) {
    int[] tab = maximum(12);
    System.out.println("Largest digit: " + tab[0]);
    System.out.println("Second largest digit: " + tab[1]);
}
public static int[] maximum(int max){
    int num = max;
    int largest = -1;
    int secondLargest = -1;
    while(num != 0){
        int rightDigit = num % 10;
        num /= 10;

        if(rightDigit > largest) {
            secondLargest = Math.max(secondLargest, largest);
            largest = rightDigit;

        } else if(rightDigit > secondLargest)
            secondLargest = rightDigit;
    }
    return new int[]{largest,secondLargest};
    }
knordbo
  • 552
  • 3
  • 7
0

Assume maxValue is the highest one and you can easily identify the second highest

   if (times[i] > maxValue) {
        secondhighest  = maxValue;
        maxValue = times[i];
    } else if (times[i] > secondhighest) {
        secondhighest  = times[i];
    }
Kalai.G
  • 1,610
  • 13
  • 22
0
int num = 1395248, n, i, n2;
for (n2 = i = n = 0; num > 0; i = num % 10, n2 = n < i ? n : n2, n = n < i ? i : n, num /= 10);
System.out.println(n);
System.out.println(n2);
Alexey Odintsov
  • 1,705
  • 11
  • 13
0

Sorting the list of number's digits and getting the 1st and 2nd biggest digits will give you at best O(n * log n) time complexity (assuming you will use Quick Sort).
You can achieve somewhat better performance if you will use another approach: partition (reorder) your array (as in quick sort), so you'll have a pivot value which divides your array in two parts: those which are less than pivot are in the left part (left sub-array), those which are bigger are in the right part (right sub-array). Check the index of the pivot:

  • if it's equal to the size of an array of digits minus 2, than it's the second biggest element (the first biggest is next to it, in the right sub-array);
  • if the index of pivot is less than size of an array of digits minus 2, repeat the partitioning for the right sub-array;
  • if the index of pivot is bigger than size of an array of digits minus 2, repeat the partitioning for the left sub-array;

At some point your pivot will be the the second element from the end of an array, which means that it's the second biggest element, and the biggest number is in the end of an array (because of the way you get the pivot). The time complexity will be better than for a quick sort, because after each partition you're partitioning only one sub-array, not both of them.

You can extend this approach to get not only the 1-st and 2-nd largest digits, but k-th (arbitrary highest) digit, and not only largest, but smallest also.

Check out the piece of code I've written couple of days ago:

public Long selectKthElement(int left, int right, int k, Type type) {
    int med = partitionIt(left, right);

    if ((type.equals(Type.Smallest) && med == k - 1) || (type.equals(Type.Largest) && med == nElems - k)) {
        return theArray[med];
    } else if (type.equals(Type.Smallest) && med > k || type.equals(Type.Largest) && med > nElems - k) {
        return selectKthElement(left, med - 1, k, type);
    } else if (type.equals(Type.Smallest) && med < k || type.equals(Type.Largest) && med < nElems - k){
        return selectKthElement(med + 1, right, k, type);
    } else {
        // impossible case, but the source code won't compile w/o the else
        return null;
    }
}

Here theArray is an array of numbers' digits, partitionIt method reorders an array and returns the index of median, you can either figure out how to write the implementation of it yourself, or search through the web.

aga
  • 27,954
  • 13
  • 86
  • 121
  • 1
    The max length of an int is 10 digits. The total run time of *any* solution won't be far off from the next solution. Might as well focus on readability and terseness rather than efficiency. – Tim Pote Nov 14 '13 at 14:51
  • @TimPote I know, it sounds childish, but I simply couldn't resist to show that I know a little bit more efficient solution. :) – aga Nov 14 '13 at 16:07
0
static void Main(string[] args)
{




    int max = 0, temp = 0, secondMax = 0, number = 0;

    number = 6541891;
    while (number != 0)
    {
        temp = number % 10;

        if (max == 0)
        {

            max = temp;
            secondMax = temp;

        }
        else if (temp > max)
        {
            int lastmax = max;

            max = temp;

            if (lastmax > secondMax)
            {
                secondMax = lastmax;
            }


        }

        if ((temp > secondMax && temp < max) || secondMax >= max)
        {
            secondMax = temp;
        }

        number = number / 10;
    }

    int Result = secondMax;

}
clemens
  • 16,716
  • 11
  • 50
  • 65
-1
    public static int nthHighest(int[] arr, int n) {
         List<Integer> lst = Arrays.asList(ArrayUtils.toObject(arr)); //use apache commons library
         Collections.sort(lst);
         return lst.get(arr.length-n);
    }
saran3h
  • 12,353
  • 4
  • 42
  • 54