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

整数与IP地址间的转换

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别

        String ip = "";
        Long numIn = -1L;
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            //s.append(in.next());
            if ("".equals(ip)) {
                ip = in.nextLine();
            } else if (numIn == -1) {
                numIn = Long.valueOf(in.nextLine());
            }
        }
        if (!"".equals(ip) && numIn > 0) {
            String[] sp = ip.split("\\.");
            int len = sp.length;
            long sum = 0;
            for (int i = 0; i < len; i++) {
                int num = Integer.valueOf(sp[i]);
                sum += to10(num, 4 - i);
            }
            System.out.println(sum);
            String numtoip = numtoip(numIn);
            System.out.println(numtoip);
            ip = "";
            numIn = -1L;
        }
    }

    private static long to10(long num, int count) {

        long base = 1;
        switch (count) {
            case 2:
                base = 256;
                break;
            case 3:
                base = 256 * 256;
                break;
            case 4:
                base = 256 * 256 * 256;
                break;
            default:
        }
        return num * base;
    }

    private static String numtoip(long num) {

        long b1 = 0, b2 = 0, b3 = 0, b4 = 0;
        if (num < 256) {
            b1 = num;
        } else if (num < 256 * 256) {
            b2 = num / 256;
            b1 = num - 256 * b2;
        } else if (num < 256 * 256 * 256) {
            b3 = num / 256 / 256;
            b2 = (num - 256 * 256 * b3) / 256;
            b1 = num - 256 * 256 * b3 - 256 * b2;
        } else {
            b4 = num / 256 / 256 / 256;
            b3 = (num - 256 * 256 * 256 * b4) / 256 / 256;
            b2 = (num - 256 * 256 * 256 * b4 - 256 * 256 * b3) / 256;
            b1 = num - 256 * 256 * 256 * b4 - 256 * 256 * b3 - 256 * b2;
        }
        return b4 + "." + b3 + "." + b2 + "." + b1;
    }
}

#刷题努力下#
雪域灰灰刷题笔记 文章被收录于专栏

雪域灰灰刷题笔记

全部评论

相关推荐

02-24 17:39
门头沟学院 Java
神哥不得了:神哥来啦~专业技能的话建议不要前面空那么多,八股的话建议先把高频top 50的八股多巩固几遍,千万不要看那些假高频八股。项目的话,建议换两个高质量的项目上去
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务