Percentage of Letter in String

Percentage of Letter in String

Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent.

LeetCode Problem - 2278

class Solution {
    public int percentageLetter(String s, char letter) {
        double countOfletter = 0; // Initialize a counter to keep track of the occurrences of the specified letter

        // Iterate over each character in the string 's'
        for (char ch : s.toCharArray()) {
            // If the current character matches the specified 'letter', increment the counter
            if (ch == letter) {
                countOfletter++;
            }
        }

        // Calculate the percentage of the specified letter in the string
        double len = s.length(); // Get the length of the string
        int result = (int) ((countOfletter / len) * 100); // Calculate the percentage and cast it to an integer

        return result; // Return the calculated percentage as an integer
    }
}