If a number is read as a String, how to Count the no of times the highest number repeated in the string?
a. Ex: 2 4 3 4 2 4 0 -> (3)


To do so,

  • Trim the given string and split it using the split() method (Removing the empty spaces in-between).
  • Create an integer array and in loop convert each element of the string array to an integer using Integer.parseInt() method and assign it to the respective element of the integer array.
  • Sort the obtained integer array, since this method sorts the elements of the array in ascending order the last element will be the maximum of the array. 
  • Create an integer variable count with initial value 0. 
  • Compare each element of the array with the maximum value, each time a match occurs increment the count. 
  • The final value of the count will be the required result.

Example

Live Demo

import java.util.Arrays;

public class CountingHighestNumber {
   public static void main(String args[]) {
      int count = 0;
      String str = "2 3 4 3 8 8 3 5 2 6 8";
      String[] strArray = str.trim().split(" ");
      int size = strArray.length;
      int[] intArray = new int[size];
     
      for(int i = 0; i<size; i++) {
         intArray[i] = Integer.parseInt(strArray[i]);
      }
      System.out.println("Integer Array ::"+Arrays.toString(intArray));
      Arrays.sort(intArray);
      System.out.println("sorted Array ::"+Arrays.toString(intArray));
      int max = intArray[size-1];
      System.out.println("Max value is :"+max);
     
      for(int i = 0; i<size; i++) {
         if(intArray[i]==max) {
            count++;
         }
      }
      System.out.println("Number of times the largest value repeated is ::"+count);
   }
}

Output

Integer Array ::[2, 3, 4, 3, 8, 8, 3, 5, 2, 6, 8]
sorted Array ::[2, 2, 3, 3, 3, 4, 5, 6, 8, 8, 8]
Max value is :8
Number of times the largest value repeated is ::3

Updated on: 16-Jun-2020

48 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements