Home  >  Article  >  How to count the number of occurrences of an integer between 0-255?

How to count the number of occurrences of an integer between 0-255?

WBOY
WBOYforward
2024-02-22 12:30:10981browse

php editor Strawberry will answer your question about how to calculate the number of occurrences of an integer between 0-255 in Java. In this problem, we can use an array with a length of 256 to record the number of times each integer appears, and then traverse the input array and add 1 to the count corresponding to the integer that appears. Finally, we can get the number of occurrences of each integer by looking up its value in the count array. This method is simple and efficient, and is suitable for calculating the number of occurrences of integers in a small range.

Question content

I have a long text file in which I have converted each character to ASCII. I want to calculate the frequency of each character after converting them to ASCII and find the most common character. So, can I create a count without typing a switch statement that contains cases for each number from 0-255?

I know that entering a count variable for each integer and doing the 256-case switch would work, but I just feel like there should be a simpler solution.

Solution

You can try to use hashmap;

Map<Integer, Integer> map = new HashMap<>();
map.put(i, map.getOrDefault(i, 0) + 1);

Then map.key is the character.ascii code, and value is its time

The above is the detailed content of How to count the number of occurrences of an integer between 0-255?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete