cpp-algo-cases/chapter_hashing/simple_hash.cpp

67 lines
1.3 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: simple_hash.cpp
* Created Time: 2023-06-21
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20>ӷ<EFBFBD><D3B7><EFBFBD>ϣ */
int addHash(string key) {
long long hash = 0;
const int MODULUS = 1000000007;
for (unsigned char c : key) {
hash = (hash + (int)c) % MODULUS;
}
return (int)hash;
}
/* <20>˷<EFBFBD><CBB7><EFBFBD>ϣ */
int mulHash(string key) {
long long hash = 0;
const int MODULUS = 1000000007;
for (unsigned char c : key) {
hash = (31 * hash + (int)c) % MODULUS;
}
return (int)hash;
}
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϣ */
int xorHash(string key) {
int hash = 0;
const int MODULUS = 1000000007;
for (unsigned char c : key) {
hash ^= (int)c;
}
return hash & MODULUS;
}
/* <20><>ת<EFBFBD><D7AA>ϣ */
int rotHash(string key) {
long long hash = 0;
const int MODULUS = 1000000007;
for (unsigned char c : key) {
hash = ((hash << 4) ^ (hash >> 28) ^ (int)c) % MODULUS;
}
return (int)hash;
}
/* Driver Code */
int main() {
string key = "Hello dsad3241241dsa<73><61>123<32><33>";
int hash = addHash(key);
cout << "<EFBFBD>ӷ<EFBFBD><EFBFBD><EFBFBD>ϣֵΪ " << hash << endl;
hash = mulHash(key);
cout << "<EFBFBD>˷<EFBFBD><EFBFBD><EFBFBD>ϣֵΪ " << hash << endl;
hash = xorHash(key);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϣֵΪ " << hash << endl;
hash = rotHash(key);
cout << "<EFBFBD><EFBFBD>ת<EFBFBD><EFBFBD>ϣֵΪ " << hash << endl;
return 0;
}