zoukankan      html  css  js  c++  java
  • python练习001-实现hashcode

      卧槽居然有人看,罪过罪过。。。

      简单说下原理:

      hash是一种常用的算法,像md5.sha,常用在安全加密等方面;

      java中hashcode是用于快速查找对象物理存储区使用的,hashcode值不存在,则可以快速存储入集合;

      java官方给出的计算hashcode的算法:

      1. Integer.hashCode()实现:

        public int hashCode(){

        return value;

         }

      就是(10进制)整数的hashcode还是它本身;

      2. String.hashCode()实现为其ACII字符码:

      public int hashCode() {
        int h = hash;
        if (h == 0) {
          int off = offset;
          char val[] = value;
          int len = count;
          for (int i = 0; i < len; i++) {
          h = 31*h + val[off++];
            }
          hash = h;
          }
        return h;
      }

      就是字符串转换成ASCII码的值:

      比如:abc, ascii表中字母对应的ASCII码分别为:97、98、99

      那么,“abc”.hashcode() = 99+98*31+97*31*31=96354

      那么知道了怎么求它,就可以在python中来计算它:

      java中str的hashcode是按照32位算的,那么在64位的python我们要考虑处理内存溢出的问题,代码如下:

      def convert_n_bytes(n, b):

          bits = b * 8

          return (n + 2 ** (bits - 1)) % 2 ** bits - 2 ** (bits - 1)

      def convert_4_bytes(n):

          return convert_n_bytes(n, 4)

      def getHashCode(str):

          h = 0

          n = len(str)

          for i, c in enumerate(str):

              h = h + ord(c) * 31 ** (n - 1 - i)

          return convert_4_bytes(h)

      print(getHashCode(input(str)))

  • 相关阅读:
    HDU 3085 Nightmare Ⅱ[双向广搜]
    HDU 4028 The time of a day [离散化DP]
    HDU4027 Can you answer these queries? [线段树]
    HDU 4331 Image Recognition [边上全为1构成的正方形个数]
    HDU4026 Unlock the Cell Phone [状态压缩DP]
    HDU 4333 Revolving Digits [扩展KMP]
    HDU4335 What is N? [数论(欧拉函数)]
    工程与管理
    项目管理笔记一
    通过100个单词掌握英语语法(七)ask
  • 原文地址:https://www.cnblogs.com/bernard-shen/p/13342136.html
Copyright © 2011-2022 走看看