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

整数与IP地址间的转换

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


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str = sc.next();
            long numIP = sc.nextLong();
            System.out.println(ipToNum(str));
            System.out.println(numToIp(numIP));
        }
    }

    public static long ipToNum(String str) {
        String[] s = str.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length; i++) {
            StringBuilder sb1 = new StringBuilder(Long.toBinaryString((Long.parseLong(s[i]))));
            sb1.reverse();
            int len = sb1.length();
            while (len < 8) {
                sb1.append("0");
                len++;
            }
            sb.append(sb1.reverse().toString());
        }
        String string = sb.toString();
        long num = Long.parseLong(string,2);
        return num;
    }

    public static String numToIp(long num) {
        String s = Long.toBinaryString(num);
        StringBuilder sb = new StringBuilder(s);
        sb = sb.reverse();
        if(sb.length() % 8 == 0){

        }else {
            int len = 8 - sb.length() % 8;
            while (len > 0) {
                sb.append("0");
                len--;
            }
        }
        sb = sb.reverse();
        s = sb.toString();
        StringBuilder sb1 = new StringBuilder();
        while (s.length() > 0) {
            if (s.length() == 8) {
                sb1.append(Long.parseLong(s.substring(0, 8), 2));
            } else {
                sb1.append(Long.parseLong(s.substring(0, 8), 2)).append(".");
            }
            s = s.substring(8);
        }
        return sb1.toString();
    }
}
全部评论

相关推荐

专心打鱼:互联网搬运工,贴子都要偷
点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务