题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String IP=sc.nextLine();
Long num=sc.nextLong();
System.out.println(ipToNum(IP));
System.out.println(NumToIp(num));
}
static long ipToNum(String IP){//将ip转换为整数(必须是Long,int溢出),赋值时要加L,不然是int
String[] str=IP.split("\\.");
long ans=0L;
for(String s:str){
long n=Long.parseLong(s);
if(n>255||n<0) return -1;
ans=ans<<8;
ans+=n;
}
return ans;
}
static String NumToIp(long num){
Deque<String> queue=new LinkedList<>();
while(num!=0){
int m=(int)(num%256);
num=num>>>8;
queue.addFirst(String.valueOf(m));
queue.addFirst(".");
}
queue.removeFirst();
String ans="";
for(String s:queue){
ans+=s;
}
return ans;
}
}