How to calculate the hash code of a string by hand?

后端 未结 3 1234
暖寄归人
暖寄归人 2021-02-02 04:44

I was wondering how to calculate the hash code for a given string by hand. I understand that in Java, you can do something like:

String me = \"What you say what          


        
3条回答
  •  逝去的感伤
    2021-02-02 05:03

    The following statements will find the string hashCode

    String str="Hi";
    
    int a = str.hashCode();//returns 2337
    

    Let's check how exactly its calculated

    HashCode = s[0]*31(n-1) + s[1]*31(n-2) + .. s(n-2)

    As we all know that the character at position 0 is H, Character at position 1 is i, and the string length is 2.

    ==> H*31(2-1) + i*31(2-2)

    As we all know that, ASCII code of H is 72, and i is 105. It means,

    ==> 72 * 31 + 105 * 1 (Anything Power 0 is 1)

    ==> 2232 + 105 = 2337

    Source: https://www.tutorialgateway.org/find-string-hashcode-in-java/

提交回复
热议问题