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

整数与IP地址间的转换

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

直接利用IP地址的进制转换。即IPV4相当于4位256进制数。 注意:直接进行进制转换可能会出现数据溢出问题,建议使用大数据类即BigInteger进行运算。

public class Main { public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    String str0=sc.nextLine();
    String str1=sc.nextLine();
    String[] str =str0.split("\\.");
    ArrayList<Integer> list =new ArrayList<>();
    for (String s : str) {
        list.add(Integer.parseInt(s));
    }
    f(str);
    f0(str1);
}
//IP 地址就是4位256进制的数,可以直接进行进制转换。
public static void f(String[] str){
    BigInteger D=new BigInteger("256");
    BigInteger bigInteger1=new BigInteger(str[0]);
    bigInteger1=bigInteger1.multiply(D).multiply(D).multiply(D);
    BigInteger bigInteger2=new BigInteger(str[1]);
    bigInteger2=bigInteger2.multiply(D).multiply(D);
    BigInteger bigInteger3=new BigInteger(str[2]);
    bigInteger3=bigInteger3.multiply(D);
    BigInteger bigInteger4=new BigInteger(str[3]);
    bigInteger1=bigInteger1.add(bigInteger2).add(bigInteger3).add(bigInteger4);
    System.out.println(bigInteger1);
}
public static void f0(String str){

    ArrayList<String> list = new ArrayList<>();
    long tem0=Long.parseLong(str);
    for (int i=0;i<4;i++){
        list.add(Long.toString(tem0 % 256));
        tem0 = tem0 / 256;
    }
    System.out.println(list.get(3)+"."+list.get(2)+"."+list.get(1)+"."+list.get(0));
}

}

全部评论

相关推荐

2025-12-06 01:10
已编辑
哈尔滨工程大学 Java
一面问的真细,二面不知为啥变双机位。9.29快手主站平时怎么学习&nbsp;AI&nbsp;的,国内外知名大模型,实习公司都用的什么大模型,怎么评估效果的java池化思想,线程池构造方法的核心参数,线程池中阻塞队列注意事项,submit方法参数和执行逻辑,shutdown和shutdownnow,核心线程允许过期吗threadlocal底层,为什么key是弱引用,key回收了再get或者set这个value会怎样aqs,如何保证公平性java代理java堆划分,新生代还有别的晋升老年代的情况吗,什么时候触发gc,gc失败抛什么异常,如何排查oom,导出dump命令redis数据结构,哪个底层是跳表,和其他数据结构对比布隆过滤器会出现大key问题吗,你咋实现的布隆过滤器你怎么实现redis分布式锁,可重入,续期聚簇索引非聚簇索引select语句会加锁吗,怎么实现的不加锁undolog&nbsp;redolog&nbsp;binlog怎么能让select加锁,update这个范围加的什么锁,update一条呢手撕简单01背包,接雨水10.10快手主站意图识别用的哪个大模型,走到意图和rag的比例,faq是点击的吗自然语言怎么识别的gap一年干啥了,转正怎么样没跟组里提意向吗,研究生研究方向是传统算法吗,会大模型微调吗注册场景为什么用布隆过滤器,原理分布式锁底层的key怎么拼的,value里是什么redis持久化zset底层mysql索引结构,一个表三个字段有主键唯一索引和没索引的字段会有几个b+树,聚簇索引非聚簇索引存的啥无手撕
点赞 评论 收藏
分享
2025-11-26 19:32
门头沟学院 Java
程序员小白条:大厂实习?都要12月了,实习都要春招的时候了,过年阶段肯定不招人
你的简历改到第几版了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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