Leetcode - Validate IP Address
https://leetcode.com/problems/validate-ip-address/
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1
;
Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01
is invalid.
IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334
is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334
is also a valid IPv6 address(Omit leading zeros and using upper cases).
func validIPAddress(IP string) string { resultV4 := check4(strings.Split(IP, ".")) resultV6 := check6(strings.Split(IP, ":")) if resultV4 { return "IPv4" } if resultV6 { return "IPv6" } return "Neither" } func check4(strs []string) bool { if len(strs) != 4 { return false } for _, str := range strs { val, err := strconv.Atoi(str) if err != nil { return false } if val > 255 || val < 0 { return false } if str[0] == '0' && len(str) > 1 { return false } if str[0] == '-' || str[0] == '+' { return false } } return true } func check6(strs []string) bool { if len(strs) != 8 { return false } for _, str := range strs { if len(str) > 4 || len(str) == 0 { return false } for i := 0; i < len(str); i++ { if !((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'f') || (str[i] >= 'A' && str[i] <= 'F')) { return false } } } return true }
Feb 16, 2023 08:06:11 AM
On the day indicated by the authorities, the board will surely post the official Class 11th Question Paper 2024 on the official website. For the time being, we are providing a Download Question Paper 2024 to help students begin their studies. +1 Question Paper 2024 We would like to emphasize that this Question Paper 2024 is only a sample that may be revised during the 2024 session.