一只烤鸭朝北走

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
class BitMap {
        private byte[] words;//用一个字节数组来存储
        private int capacity;//位图的长度

        public BitMap(int capacity) {
            this.capacity = capacity;
            words = new byte[((capacity - 1) >> 3) + 1];
        }

        /**
         * @Title: setBit 
         * @Description: 
         * @param num
         */
        public void setBit(int num) {
            if (num < 0 || num > capacity) {
                return;
            }
            int index = num >> 3;
            int position = num & 0x7;
            words[index] |= (1 << position);
        }

        /**
         * 
         * @Title: contains 
         * @Description:  判断某个数是否存在
         * @param num
         * @return
         */
        public boolean contains(int num) {
            if (num < 0 || num > capacity) {
                return false;
            }
            int index = num >> 3;
            int position = num & 0x7;
            return (words[index] & (1 << position)) != 0;
        }

        /**
         * 
         * @Title: clear 
         * @Description:  清除某个值
         * @param num
         */
        public void clear(int num) {
            if (num < 0 || num > capacity) {
                return;
            }
            int index = num >> 3;
            int position = num & 0x7;
            words[index] &= ~(1 << position);
        }
    }

 

posted on 2021-07-20 15:04  一只烤鸭朝北走  阅读(68)  评论(0)    收藏  举报