算法學習記錄——Bitmap位圖算法應用(JAVA實現)

 Bitmap--->位圖算法的應用——適用於大整數的--->去重和查找

//Bitmap--->位圖算法的應用——適用於大整數的——去重和查找
public class TheBitmap {
	
	//用long長整形作爲存儲數據的二進制位,每個佔用64bit位,即可以存儲64個數據(0——63),也就是每一個words[]就可以表示64個整數。
	//words[0]--->0-63
	//words[1]--->64-127
	//words[n]--->以此類推即可
	//用所要查找或者存儲的整數-->n,除以64即爲words的數組元素的數量
	private long[] words;
	//size表示當前數組words所能存儲的整數的最大範圍,也就是上面n的最大值。
	private int size;
	
	public TheBitmap(int size) {
		this.size=size;
		words=new long[getWordIndex(size-1)+1];
	}
	
	
	//計算words數組裏的元素個數——因爲是long類型,每個的存儲空間爲64bit位,所以要以64爲一個單位存儲長度進行計算。
	private int getWordIndex(int bitIndex) {
		// TODO Auto-generated method stub
		//bitIndex的二進制數位右移6位,相當於十進制除以2的6次方-->64
		return bitIndex>>6;
	}

	//將words數組中的某一個元素對應的二進制中的某一位(即 bitIndex位)設置爲1
	public void setBit(int bitIndex) {
		
		if(bitIndex<0 || bitIndex>size-1) {
			throw new IndexOutOfBoundsException(" 超過Bitmap有效範圍");
		}
		
		int wordIndex=getWordIndex(bitIndex);
		
		//用或運算,將bitIndex轉化成二進制之後,在words[]轉換成二進制後相對應的位置置爲1.
		words[wordIndex]=words[wordIndex] | (1L << bitIndex);
		
	}
	
	public boolean getBit(int bitIndex) {
		
		if(bitIndex<0 || bitIndex>size-1) {
			throw new IndexOutOfBoundsException(" 超過Bitmap有效範圍");
		}
		
		int wordIndex=getWordIndex(bitIndex);
		
		//用與運算,將bitIndex轉化成二進制之後,與在words[]轉換成二進制後,進行與運算,好確認是否在words[]中已經存在1
		return (words[wordIndex] & (1L << bitIndex))!=0;
	}
	


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TheBitmap bitmap=new TheBitmap(128);
		
		bitmap.setBit(126);
		bitmap.setBit(75);
		
		System.out.println(bitmap.getBit(126));
		System.out.println(bitmap.getBit(75));
		System.out.println(bitmap.getBit(60));
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章