题解 | #整数与IP地址间的转换#

整数与IP地址间的转换

https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

import java.util.Scanner;
import java.math.BigInteger;
import java.util.Scanner;


//注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            String b = in.nextLine();
            System.out.println(getIpChangeInt(a));
            System.out.println(getIntChangeIp(b));
        }
        in.close();

    }
    private static Long  getIpChangeInt(String str) {
        String[] arr = str.split("\\.");
        String res = Integer.toBinaryString(Integer.parseInt(arr[0]));
        for (int i = 1; i < arr.length; i++) {
            String s = "00000000" + Integer.toBinaryString(Integer.parseInt(arr[i]));
            res += s.substring(s.length() - 8, s.length());
        }
	  //此处int 会溢出
        return Long.parseLong(res,2);
    }

    private static String  getIntChangeIp(String str) {
       //此处int 会溢
        BigInteger b = new BigInteger(str);
	    String res = "00000000"+b.toString(2);
        String[] s1 = new String[4];
        String ip = "";
        for (int i = 0; i < 4; i++) {
            s1[i] = res.substring(res.length() - 8, res.length());
            res = res.substring(0, res.length() - 8);
        }
        for (int i = 0; i < 3; i++) {
            ip += Integer.parseInt(s1[3 - i], 2);
            ip += ".";
        }
        return ip + Integer.parseInt(s1[0], 2);

    }
}

全部评论

相关推荐

牛客868257804号:九个中铁八个中建
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务