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

整数与IP地址间的转换

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

import java.util.*;

/*

* */
public class Main{

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String ip = sc.next();
        long l = sc.nextLong();
        System.out.println(yip(ip));
        System.out.println(dip(l));
    }

    //10进制转ip
    private static String dip(long num){
        String s = Long.toBinaryString(num);
        String[] strings = new String[4];
        while (s.length() < 32){
            s = "0" + s;
        }
        for (int i = 0; i < 4; i++) {
            String substring = s.substring(i * 8, i * 8 + 8);
            int i1 = Integer.parseInt(substring, 2);
            strings[i] = String.valueOf(i1);
        }
        return String.join(".",strings);
    }

    //ip转10进制
    private static long yip(String str){
        String[] split = str.split("[.]");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            int i1 = Integer.parseInt(split[i]);
            String s = Integer.toBinaryString(i1);
            while (s.length() < 8){
                s = "0" + s;
            }
            sb.append(s);
        }
        return Long.parseLong(sb.toString(),2);
    }
}
全部评论

相关推荐

已老实求offer😫:有点像徐坤(没有冒犯的意思哈)
点赞 评论 收藏
分享
头像
11-21 11:39
四川大学 Java
是红鸢啊:忘了还没结束,还有字节的5k 违约金
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务