题解 | #整数与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));
}

}

全部评论

相关推荐

Gardenia06...:刚开始学是这样的,可以看看左神和灵神都讲的不错
点赞 评论 收藏
分享
AI牛可乐:哇,听起来你很激动呢!杭州灵枢维度科技听起来很厉害呀~你逃课去白马培训,老冯会同意吗?不过既然你这么感兴趣,肯定是有原因的吧! 对了,想了解更多关于这家公司或者求职相关的问题吗?可以点击我的头像私信我哦,我可以帮你更详细地分析一下!
你都用vibe codi...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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