题解 | 整数与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);
        while (in.hasNext()) {
            String str = in.next();
            String res = getResult(str);
            System.out.println(res);
        }
    }

    public static String getResult(String str) {
        if (str.indexOf(".") > 0) {
            String[] split = str.split("\\.");
            Long result = 0L;
            int pow = 0;
            for (int i = 3; i >= 0; i--) {
                result += Long.parseLong(split[i]) * (int) Math.pow(256, pow++);
            }
            return String.valueOf(result);
        } else {
            long result = Long.parseLong(str);
            StringBuilder builder = new StringBuilder();
            int pow = 3;
            while (result > 0) {
                long num = result / (int)Math.pow(256, pow);
                builder.append(num).append(".");
                result = result % (int)Math.pow(256, pow);
                pow--;
            }
            return builder.substring(0, builder.length() - 1);
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务