mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-27 19:06:28 +08:00
3f4220de81
* preorder, inorder, postorder -> pre-order, in-order, post-order * Bug fixes * Bug fixes * Update what_is_dsa.md * Sync zh and zh-hant versions * Sync zh and zh-hant versions. * Update performance_evaluation.md and time_complexity.md * Add @khoaxuantu to the landing page. * Sync zh and zh-hant versions * Add @ khoaxuantu to the landing page of zh-hant and en versions.
66 lines
1.4 KiB
C++
66 lines
1.4 KiB
C++
/**
|
|
* File: simple_hash.cpp
|
|
* Created Time: 2023-06-21
|
|
* Author: krahets (krahets@163.com)
|
|
*/
|
|
|
|
#include "../utils/common.hpp"
|
|
|
|
/* 加法雜湊 */
|
|
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;
|
|
}
|
|
|
|
/* 乘法雜湊 */
|
|
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;
|
|
}
|
|
|
|
/* 互斥或雜湊 */
|
|
int xorHash(string key) {
|
|
int hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
for (unsigned char c : key) {
|
|
hash ^= (int)c;
|
|
}
|
|
return hash & MODULUS;
|
|
}
|
|
|
|
/* 旋轉雜湊 */
|
|
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 演算法";
|
|
|
|
int hash = addHash(key);
|
|
cout << "加法雜湊值為 " << hash << endl;
|
|
|
|
hash = mulHash(key);
|
|
cout << "乘法雜湊值為 " << hash << endl;
|
|
|
|
hash = xorHash(key);
|
|
cout << "互斥或雜湊值為 " << hash << endl;
|
|
|
|
hash = rotHash(key);
|
|
cout << "旋轉雜湊值為 " << hash << endl;
|
|
|
|
return 0;
|
|
}
|