题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static long ipToLong(String ipAddress) { String[] ipAddressInArray = ipAddress.split("\\."); long result = 0; for (int i = 0; i < 4; i++) { int octet = Integer.parseInt(ipAddressInArray[i]); result += ((long) octet & 0xFF) << (8 * (3 - i)); } return result; } public static String LongToIp(long longValue) { StringBuilder ipAddress = new StringBuilder(); for (int i = 3; i >= 0; i--) { int octet = (int) ((longValue >> (8 * i)) & 0xFF); ipAddress.append(octet); if (i > 0) { ipAddress.append("."); } } return ipAddress.toString(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String ipAddress = sc.nextLine(); Long longValue2 = Long.valueOf(sc.nextLine()); System.out.println(ipToLong(ipAddress)); System.out.println(LongToIp(longValue2)); } }