Files
hello-algo/ja/codes/java/chapter_hashing/simple_hash.java
T
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

66 lines
1.7 KiB
Java

/**
* File: simple_hash.java
* Created Time: 2023-06-21
* Author: krahets ([email protected])
*/
package chapter_hashing;
public class simple_hash {
/* 加算ハッシュ */
static int addHash(String key) {
long hash = 0;
final int MODULUS = 1000000007;
for (char c : key.toCharArray()) {
hash = (hash + (int) c) % MODULUS;
}
return (int) hash;
}
/* 乗算ハッシュ */
static int mulHash(String key) {
long hash = 0;
final int MODULUS = 1000000007;
for (char c : key.toCharArray()) {
hash = (31 * hash + (int) c) % MODULUS;
}
return (int) hash;
}
/* 排他的論理和ハッシュ */
static int xorHash(String key) {
int hash = 0;
final int MODULUS = 1000000007;
for (char c : key.toCharArray()) {
hash ^= (int) c;
}
return hash & MODULUS;
}
/* 回転ハッシュ */
static int rotHash(String key) {
long hash = 0;
final int MODULUS = 1000000007;
for (char c : key.toCharArray()) {
hash = ((hash << 4) ^ (hash >> 28) ^ (int) c) % MODULUS;
}
return (int) hash;
}
public static void main(String[] args) {
String key = "Hello 算法";
int hash = addHash(key);
System.out.println("加算ハッシュの値は " + hash);
hash = mulHash(key);
System.out.println("乗算ハッシュの値は " + hash);
hash = xorHash(key);
System.out.println("排他的論理和ハッシュの値は " + hash);
hash = rotHash(key);
System.out.println("回転ハッシュの値は " + hash);
}
}