哈希运算的伪代码
Pseudocode for Hashing Operation
我正在学习 Data Structures Problem Solving Using Java
这本书,并被要求提供书中给定函数的第 5 行的详细伪代码。显然第 5 行相当于 16 位二进制数的加法和移位,但我不明白它是如何工作的。
我有基本的 Java 背景,并将第 5 行理解为一个存储变量乘以 37 并加上循环迭代到的当前字母(我假设它随后被转换为添加到 int
hashVal
).
时的 ASCII 字符
public static int hash( String key, int tableSize ) {
int hashVal = 0;
for( int i = 0; i < key.length( ); i++ )
hashVal = 37 * hashVal + key.charAt( i ); // line 5
hashVal %= tableSize;
if( hashVal < 0 )
hashVal += tableSize;
return hashVal;
}
谁能帮我解释一下第 5 行和 16 位二进制数的加法和移位有什么关系?换句话说,如何用伪代码描述第 5 行以符合该定义?
他们可能指的是将 key.charAt(i)
隐式转换为 int
; char
s 在内部表示为 16 位数字。仅此而已——这就是 char
的表示和转换为 int
的方式。详情见http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html:
The char data type (and therefore the value that a Character object encapsulates) are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. The Unicode Standard has since been changed to allow for characters whose representation requires more than 16 bits. The range of legal code points is now U+0000 to U+10FFFF, known as Unicode scalar value. (Refer to the definition of the U+n notation in the Unicode Standard.)
我正在学习 Data Structures Problem Solving Using Java
这本书,并被要求提供书中给定函数的第 5 行的详细伪代码。显然第 5 行相当于 16 位二进制数的加法和移位,但我不明白它是如何工作的。
我有基本的 Java 背景,并将第 5 行理解为一个存储变量乘以 37 并加上循环迭代到的当前字母(我假设它随后被转换为添加到 int
hashVal
).
public static int hash( String key, int tableSize ) {
int hashVal = 0;
for( int i = 0; i < key.length( ); i++ )
hashVal = 37 * hashVal + key.charAt( i ); // line 5
hashVal %= tableSize;
if( hashVal < 0 )
hashVal += tableSize;
return hashVal;
}
谁能帮我解释一下第 5 行和 16 位二进制数的加法和移位有什么关系?换句话说,如何用伪代码描述第 5 行以符合该定义?
他们可能指的是将 key.charAt(i)
隐式转换为 int
; char
s 在内部表示为 16 位数字。仅此而已——这就是 char
的表示和转换为 int
的方式。详情见http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html:
The char data type (and therefore the value that a Character object encapsulates) are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. The Unicode Standard has since been changed to allow for characters whose representation requires more than 16 bits. The range of legal code points is now U+0000 to U+10FFFF, known as Unicode scalar value. (Refer to the definition of the U+n notation in the Unicode Standard.)