文章目录
- 题目描述
- 输入描述
- 输出描述
- 用例
- C++
- java
- javaScript
- python
题目描述
存在一种虚拟IPv4地址,由4小节组成,每节的范围为0~255,以#号间隔,虚拟IPv4地址可以转换为一个32位的整数,例如:
128#0#255#255,转换为32位整数的结果为2147549183(0x8000FFFF)
1#0#0#0,转换为32位整数的结果为16777216(0x01000000)
现以字符串形式给出一个虚拟IPv4地址,限制第1小节的范围为1128,即每一节范围分别为(1128)#(0255)#(0255)#(0~255),要求每个IPv4地址只能对应到唯一的整数上。如果是非法IPv4,返回invalid IP
输入描述
输入一行,虚拟IPv4地址格式字符串
输出描述
输出一行,按照要求输出整型或者特定字符
用例
输入 | 100#101#1#5 |
输出 | 1684340997 |
说明 | 无 |
C++
#include <iostream>
#include <string>
using namespace std;int main() {string ip;getline(cin, ip); // 输入虚拟IPv4地址字符串int p1, p2, p3, p4;sscanf(ip.c_str(), "%d#%d#%d#%d", &p1, &p2, &p3, &p4); // 解析字符串为四个整数if (p1 >= 1 && p1 <= 128 && p2 >= 0 && p2 <= 255 && p3 >= 0 && p3 <= 255 && p4 >= 0 && p4 <= 255) {// 判断是否为合法的虚拟IPv4地址string res = "";int arr[4] = {p1, p2, p3, p4};for (int i = 0; i < 4; i++) {char buf[3];sprintf(buf, "%02X", arr[i]); // 将每个整数转换为两位16进制数res += buf;}cout << stoi(res, nullptr, 16) << endl; // 将16进制字符串转换为整数并输出} else {cout << "invalid IP" << endl;}return 0;
}
java
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String ip = sc.nextLine(); // 输入虚拟IPv4地址字符串int p1, p2, p3, p4;String[] parts = ip.split("#");p1 = Integer.parseInt(parts[0]);p2 = Integer.parseInt(parts[1]);p3 = Integer.parseInt(parts[2]);p4 = Integer.parseInt(parts[3]); // 解析字符串为四个整数if (p1 >= 1 && p1 <= 128 && p2 >= 0 && p2 <= 255 && p3 >= 0 && p3 <= 255 && p4 >= 0 && p4 <= 255) {// 判断是否为合法的虚拟IPv4地址String res = "";int[] arr = {p1, p2, p3, p4};for (int i = 0; i < 4; i++) {String hex = Integer.toHexString(arr[i]).toUpperCase();if (hex.length() == 1) {hex = "0" + hex;}res += hex;}System.out.println(Integer.parseInt(res, 16)); // 将16进制字符串转换为整数并输出} else {System.out.println("invalid IP");}}
}
javaScript
const readline = require('readline');
const rl = readline.createInterface({input: process.stdin,output: process.stdout
});rl.on('line', (input) => {const ip = input.trim(); // 输入虚拟IPv4地址字符串let [p1, p2, p3, p4] = ip.split("#").map(Number); // 解析字符串为四个整数if (p1 >= 1 && p1 <= 128 && p2 >= 0 && p2 <= 255 && p3 >= 0 && p3 <= 255 && p4 >= 0 && p4 <= 255) {// 判断是否为合法的虚拟IPv4地址let res = "";const arr = [p1, p2, p3, p4];for (let i = 0; i < 4; i++) {let hex = arr[i].toString(16).toUpperCase();if (hex.length === 1) {hex = "0" + hex;}res += hex;}console.log(parseInt(res, 16)); // 将16进制字符串转换为整数并输出} else {console.log("invalid IP");}
});
python
import reip = input()
match = re.match(r'^(\d{1,3})#(\d{1,3})#(\d{1,3})#(\d{1,3})$', ip)
if match:p1, p2, p3, p4 = map(int, match.groups())if 1 <= p1 <= 128 and 0 <= p2 <= 255 and 0 <= p3 <= 255 and 0 <= p4 <= 255:arr = [p1, p2, p3, p4]res = ''.join([hex(x)[2:].zfill(2).upper() for x in arr])print(int(res, 16))else:print("invalid IP")
else:print("invalid IP")