首页 > 试题广场 >

IP地址转化

[编程题]IP地址转化
  • 热度指数:900 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
IP地址是一个用 '.' 隔开的四段数字,每段的大小是 。请你把 IP 地址转换成一个整数。(IPv4)
例如, 114.55.207.244 的二进制表示是 01110010 00110111 11001111 11110100 ,其十进制表示是 7590617063
示例1

输入

"114.55.207.244"

输出

"1916260340"
示例2

输入

"0.0.0.1"

输出

"1"
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param ip string字符串 
     * @return string字符串
     */
    public String IPtoNum(String ip) {
        // write code here
        String[] split = ip.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            String s = Integer.toBinaryString(Integer.parseInt(split[i]));
            // 如果不够位数,首尾补0
            while (s.length() < 8) {
                s = "0" + s;
            }
            sb.append(s);
        }
        return String.valueOf(Long.parseLong(sb.toString(), 2));
    }
}

发表于 2022-04-12 22:47:53 回复(0)
两种方法,一种用String的split和Integer.toBinaryString,一种用StringBuilder和BigInteger
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param ip string字符串 
     * @return string字符串
     */
    public String IPtoNum (String ip) {
        // write code here
        String[] strNum = ip.split("\\.");
        String strLevel = "";
        for (String str : strNum){
            String strLengthFill = Integer.toBinaryString(Integer.parseInt(str));
            int J = 8 - strLengthFill.length();
            for (int j = 0; j < (J) ; j++)
                strLengthFill = "0" + strLengthFill;
            strLevel = strLevel + strLengthFill;
        }
        return new BigInteger(strLevel, 2).toString();
    }
    
/*
    public static String IPtoNum (String ip) {
        // write code here
        StringBuilder strNum = new StringBuilder("");
        StringBuilder strBblank = new StringBuilder("");
        StringBuilder strB = new StringBuilder(ip);
        strB.append(".");
        BigInteger bigInt = new BigInteger("0",10);
        for ( int i = 0 ; i < strB.length() ; i++ ){
            if (strB.charAt(i)!='.') {
                strBblank.append(strB.charAt(i));
            }else{
                bigInt = new BigInteger(strBblank.toString(), 10);
                String strLengthFill = bigInt.toString(2);
                int J = 8 - strLengthFill.length();
                for (int j = 0; j < (J) ; j++)
                    strLengthFill = "0" + strLengthFill;
                strNum.append(strLengthFill);
                strBblank = new StringBuilder("");
            }
        }
        bigInt = new BigInteger(strNum.toString(), 2);
        return bigInt.toString();
    }*/
}

发表于 2022-03-15 21:06:36 回复(0)