首页 > 试题广场 >

IP地址转化

[编程题]IP地址转化
  • 热度指数:880 时间限制: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)
#include <algorithm>
#include <iterator>
#include <string>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param ip string字符串 
     * @return string字符串
     */
    string fill_l(string t){   //不足8位向最左边填充0
        while(t.size()<8) t.insert(0,"0");
        return t;
    }
    
    string transform(string n){    //将十进制数转换为二进制数
          int a=stoi(n);
          string str="";
          while(a){
            int t=a%2;
            str+=to_string(t);
            a/=2;
          }
          reverse(str.begin(),str.end());
        return str;
    }
    string IPtoNum(string ip) {
        // write code here
        stack<string> stk;
        string std="";
        string str="";
        for(int i=0;i<ip.size();i++){   //堆栈存储各段数字
             if(ip[i]!='.'){
                std+=ip[i];
             }
             else{
                stk.push(std);
                std="";
             }
        }
        if(std.size()!=0) stk.push(std);
        std.clear();     
        while(!stk.empty()){ //求二进制字符串
            string g=fill_l(transform(stk.top()));
            reverse(g.begin(),g.end());
            std+=g;
            stk.pop();
        }

        long long sum=0;       //求十进制值
        for(int i=0;i<std.size();i++){
             sum+=pow(2,i)*(std[i]-'0');
        }
        return to_string(sum);
    }
};

发表于 2024-03-24 19:44:42 回复(0)
#include<bits/stdc++.h>
using namespace std;
union u{
    unsigned char ch[4];
    unsigned int n;
};
int main(){
    u m;
//    发现不能用下边这方式读取
//    scanf("%d.%d.%d.%d",&m.ch[3],&m.ch[2],&m.ch[1],&m.ch[0]);
    int a,b,c,d;
    scanf("%d.%d.%d.%d",&a,&b,&c,&d);
    m.ch[0]=d;
    m.ch[1]=c;
    m.ch[2]=b;
    m.ch[3]=a;
    printf("%u",m.n);
    return 0;
}

编辑于 2024-03-24 17:16:32 回复(0)
class Solution {
public:
    string IPtoNum(string ip) {
        unsigned int ipInt = 0;

        int i = -1;

        for(int j = 0; j < 4; j++) {
            i++;
            int len = min(i + 4, ip.length());
            int num = -1;
            for(; i < len; i++) {
                if(ip[i] == '.') 
                    break;
                else if(ip[i] >= '0' && ip[i] <= '9') {
                    if(num == -1) 
                        num = 0;
                    num = num*10 + (int)(ip[i] - '0');
                }
                else 
                    return "";
            }
            if(num > 255 || num < 0)
                return "";

            ipInt += (num << (3 - j) * 8);
        }
        return to_string(ipInt);
    }

    int min(int a, int b) {
        return a < b ? a : b;
    }
};

发表于 2023-03-10 10:10:40 回复(0)
import socket, struct
class Solution:
    def IPtoNum(self , ip: str) -> str:
        packedIP = socket.inet_aton(ip)
        return struct.unpack("!L", packedIP)[0]

发表于 2022-11-19 10:48:31 回复(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)

问题信息

难度:
6条回答 2225浏览

热门推荐

通过挑战的用户

查看代码