折叠法哈希函数的数字格式异常

Number Format Exception for Folding Method Hash Function

我使用折叠方法编写了一个散列函数,这样 "ape" &"pea" 等字谜将散列为相同的值。到目前为止,我放入其中的大多数字符串都有效。但在某些情况下,我会遇到数字格式异常。

例如,当我传递 table 大小为 109 的字符串 "abalone" 时,会弹出异常,而字符串 "abalon" 则不会。

private static int Hash(String theString,int theTableSize){
    //ignore case and remove all non-alphanumeric characters
    String temp = theString.toLowerCase();
    temp = temp.replaceAll("[^a-zA-Z0-9]", "");

    //sort to count # and type of characters when hashing, NOT alphabetical order
    char[] arr = temp.toCharArray();
    Arrays.sort(arr);
    temp = new String(arr);

    //Folding Method for Hash
    String str_A = temp.substring(0, temp.length()/2);
    String str_B = temp.substring(temp.length()/2, temp.length());

    System.out.println(str_A + " " + str_B );

    return (folding(str_A) + folding(str_B)) % theTableSize;
}

private static int folding(String substring){
    int x = 0;
    for(int i = 0; i < substring.length(); i++){
        int tchar = substring.charAt(i);
        String schar = Integer.toString(tchar);
        System.out.println(schar);
        x = Integer.parseInt(x + schar) ;
        x = Math.abs(x);
    }
    return x;
}

有什么我遗漏的吗?

问题似乎是行

x = Integer.parseInt(x + schar);

您在这里连接字符串,因此参数 x + schar 可能比 int 的最大长度更长。

A java int 是 32 位。您尝试解析的数字是 979897108111,超过 32 位。