Home > Java > body text

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

WBOY
Release: 2024-02-22 12:30:10
forward
955 people have browsed it

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);
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!