java算法(三十五)
1、判断二进制里1的个数。
public static void main(String[] args) { int num =0; Scanner sc = new Scanner(System.in); while (sc.hasNext()){ int n = sc.nextInt(); num = fun(n); System.out.println(n+"的二进制里1的个数为"+num+"个"); } } private static int fun(int n){ int num =0; String str = Integer.toBinaryString(n); System.out.println(str); int len = str.length(); for(int i=0; i<len; i++){ if(str.charAt(i) == '1'){ num++; } } return num; }
2、如何把一个ip转化为int数字,实现互相转化.
public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()){ String str = sc.nextLine(); long res = fun(str); System.out.println(res); System.out.println(fun2(res)); } } private static String fun2(long res) { StringBuilder str = new StringBuilder(); str.append(String.valueOf(res >> 24) + "."); str.append(String.valueOf((res & 0x00FFFFFF) >> 16)+"."); str.append(String.valueOf((res & 0x0000FFFF) >> 8)+"."); str.append(String.valueOf((res & 0x000000FF))); return str.toString(); } private static long fun(String str){ String[] ip = str.split("\\."); for(String str1: ip){ System.out.println(str1); } return (Integer.parseInt(ip[0]) << 24) + (Integer.parseInt(ip[1]) << 16) + (Integer.parseInt(ip[2]) << 8) + Integer.parseInt(ip[3]); }
算法 文章被收录于专栏
根据自己所见所闻进行算法归纳总结