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

整数与IP地址间的转换

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

toBinaryString 和 parseInt进制的运行而已。


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        StringBuilder sb = new StringBuilder();
        while (in.hasNextLine()) {
            String ip = in.nextLine();
            sb.setLength(0);
            if (ip.contains(".")) {
                String[] ips = ip.split("\\.");
                for (int a = 0; a < ips.length; a++) {
                    String b = Integer.toBinaryString(Integer.parseInt(ips[a]));
                    sb.append(g(8 - b.length()) + b);
                }
                System.out.println(Long.parseLong(sb.toString(), 2));
            } else {
                String binaryString = Long.toBinaryString(Long.parseLong(ip));
                binaryString = g(32 - binaryString.length()) + binaryString;
                for (int a = 0; a < 32; a = a + 8) {
                    sb.append(Integer.parseInt(binaryString.substring(a, a + 8), 2));
                    if (a < 24) {
                        sb.append(".");
                    }
                }
                System.out.println(sb.toString());
            }
        }
    }
    
    private static String g(int  a) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < a; i++) {
            sb.append("0");
        }
        return sb.toString();
    }
}
全部评论

相关推荐

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