โจทย์
ได้รับสตริง str ประกอบด้วยตัวอักษรอังกฤษ ทางเราต้อง หาตำแหน่งของแต่ละตัวอักษรในอัลฟาเบทโดยใช้บิตเวิร์ก
ไม่สนใจตัวพิมพ์เล็ก/ใหญ่ (Case-insensitive)
ตัวอย่าง
Input: str = "Tutorialspoint"
Output: 20 21 20 15 18 9 1 12 19 16 15 9 14 20
แนวทางแก้ปัญหา
รหัส ASCII ของ 'A' = 65 (0b1000001), 'a' = 97 (0b1100001)
ทำ AND กับ 31 (0b11111) จะได้ตำแหน่ง 1-26:
- 'A' & 31 = 1, 'B' & 31 = 2, ..., 'Z' & 31 = 26
- 'a' & 31 = 1, 'b' & 31 = 2, ..., 'z' & 31 = 26
โปรแกรมตัวอย่าง
#include <iostream>
using namespace std;
void findLetterPosition(string str, int n) {
for (int i = 0; i < n; i++)
cout << (str[i] & 31) << " ";
}
int main() {
string str = "TutorialsPoint";
int n = str.length();
cout << "The letters position in string " << str << " is \n";
findLetterPosition(str, n);
return 0;
}
ผลลัพธ์
The letters position in string TutorialsPoint is 20 21 20 15 18 9 1 12 19 16 15 9 14 20