3120. Count the Number of Special Characters I
/**
* Problem: LeetCode 3120 - Count the Number of Special Characters I
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int numberOfSpecialChars(String word) {
int lowerMask = 0;
int upperMask = 0;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch >= 'a' && ch <= 'z') {
lowerMask |= (1 << (ch - 'a'));
} else if (ch >= 'A' && ch <= 'Z') {
upperMask |= (1 << (ch - 'A'));
}
}
return Integer.bitCount(lowerMask & upperMask);
}
}
"""
Problem: LeetCode 3120 - Count the Number of Special Characters I
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
class Solution:
def numberOfSpecialChars(self, word: str) -> int:
lower_mask = 0
upper_mask = 0
for ch in word:
if 'a' <= ch <= 'z':
lower_mask |= (1 << (ord(ch) - ord('a')))
elif 'A' <= ch <= 'Z':
upper_mask |= (1 << (ord(ch) - ord('A')))
return (lower_mask & upper_mask).bit_count()
/**
* Problem: LeetCode 3120 - Count the Number of Special Characters I
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <string>
using namespace std;
class Solution {
public:
int numberOfSpecialChars(string word) {
int lowerMask = 0;
int upperMask = 0;
for (char ch : word) {
if (ch >= 'a' && ch <= 'z') {
lowerMask |= (1 << (ch - 'a'));
} else if (ch >= 'A' && ch <= 'Z') {
upperMask |= (1 << (ch - 'A'));
}
}
return __builtin_popcount(lowerMask & upperMask);
}
};
/**
* Problem: LeetCode 3120 - Count the Number of Special Characters I
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {string} word
* @return {number}
*/
var numberOfSpecialChars = function(word) {
let lowerMask = 0;
let upperMask = 0;
for (let i = 0; i < word.length; i++) {
const code = word.charCodeAt(i);
if (code >= 97 && code <= 122) { // 'a' - 'z'
lowerMask |= (1 << (code - 97));
} else if (code >= 65 && code <= 90) { // 'A' - 'Z'
upperMask |= (1 << (code - 65));
}
}
let common = lowerMask & upperMask;
let count = 0;
while (common > 0) {
common &= (common - 1);
count++;
}
return count;
};