使用二分尋找判斷IP地區區間測試,ip地區

來源:互聯網
上載者:User

使用二分尋找判斷IP地區區間測試,ip地區

IP地址都是轉換成Long型,每個地區以IP段表示,通過二分尋找判斷IP地址落在哪個段。





package hello;

import java.util.*;


public class datatest {


public static void main(String[] args) throws InterruptedException {
final HashMap<Integer, String> map = new HashMap<Integer, String>();
final String DELIMITER = "\t";
String line = ("1677721616777471澳大利亞");
String[] str = line.split(DELIMITER);
Integer key_begin = Integer.parseInt(str[0].trim());
Integer key_end = Integer.parseInt(str[1].trim());
String country = str[2].trim();
// System.out.println(key_begin+" "+" " +country);
map.put(key_begin, country);
ArrayList<Integer> list = new ArrayList<Integer>();
Integer ip = 16777473;


list.add(16777216);
list.add(16777472);
list.add(16778240);
list.add(16779264);
list.add(16777471);
list.add(16778239);
list.add(16779263);
list.add(16781311);
Collections.sort(list);
System.out.println(list.toString());


// [16777216, 16777471, 16777472, 16778239, 16778240, 16779263, 16779264, 16781311]
int low = 0;
int high = list.size();
int middle;
int value;
while (low <= high) {
middle = (low + high) / 2;
value = list.get(middle);
System.out.println("middle="+middle+" and value="+value);
Thread.sleep(300);
if (ip < list.get(middle)) {
high = middle - 1;
} else if (ip > list.get(middle)) {
       low = middle + 1;
System.out.println(high+" "+low);
Thread.sleep(300);
}
}System.out.println(high+" "+list.get(high));
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.