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

整数与IP地址间的转换

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = null;
        str = br.readLine();
        ipToNum(str);
        numToIp(br.readLine());
    }

    public static void numToIp(String str) {
        String string = Long.toBinaryString(Long.parseLong(str));
        if (string.length() < 32) {
            int len = 32 - string.length();
            while (len != 0) {
                string = "0" + string;
                len--;
            }
        }
        long[] l = new long[4];
        for (int i = 8, j = 0; i<= string.length(); j++) {
            String temp = string.substring(0, 8);
            l[j] = Long.parseLong(temp, 2);
            string = string.substring(8);
        }

        for (int i = 0; i < l.length; i++) {
            System.out.print(l[i]);
            if (i != l.length - 1) {
                System.out.print(".");
            }
        }

    }

    public static void ipToNum(String str) {
        String[] split = str.split("\\.");
        String temp = "";

        for (int i = 0; i < split.length; i++) {
            String ip = Integer.toBinaryString(Integer.parseInt(split[i]));
            if (ip.length() < 8) {
                int len = 8 - ip.length();
                while (len != 0) {
                    ip = "0" + ip;
                    len--;
                }
            }
            temp += ip + "";
        }
        System.out.println(Long.parseLong(temp, 2));
    }

}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务