题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.ArrayList; import java.util.Scanner; /** * @author ChrisPeng * @date 2023/2/2 17:41 */ public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String ipA = scanner.nextLine(); long ipB = scanner.nextLong(); String[] split = ipA.split("\\."); long digitIP = 0; for (int i = 0; i < split.length; i++) { digitIP += Math.pow(2, 8 * (3 - i)) * Integer.parseInt(split[i]); } //将十进制转换为ip地址:点分十进制 StringBuilder sb = new StringBuilder(); ArrayList<Integer> list = new ArrayList<>(); while (ipB > 0) { int temp = (int) (ipB % 256); ipB /= 256; list.add(temp); } sb.append(list.get(3)).append(".") .append(list.get(2)).append(".") .append(list.get(1)).append(".") .append(list.get(0)); System.out.println(digitIP); System.out.println(sb.toString()); } } }