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

整数与IP地址间的转换

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

import java.util.*;

// 思路是借鉴最高赞
// 没有额外写转换函数
// *这里注意contains是不需要转义的,而split需要
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        
        while (in.hasNextLine()) {
            String line = in.nextLine();
            if (line == null || line == "") break;
            Long ans = 0L;
            Long cur = 0L;
            String res = "";
            
            if (line.contains(".")) {
                String[] ip = line.split("\\.");
                for (int i = 0; i < ip.length; i++) {
                    cur += Long.parseLong(ip[i]);
                    ans = cur;
                    cur *= 256;
                }
                System.out.println(ans);

            } else {
                Long num = Long.parseLong(line);
                
                while (num > 0) {
                    cur = num % 256;
                    num /= 256;
                    res = cur + "." + res;
                }
                System.out.println(res.substring(0, res.length() - 1));
                
            }
            
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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