Skip to content

468. 验证 IP 地址

Posted on:2022年10月26日 at 14:18

468. 验证 IP 地址

leetcode 链接

解法一:依次遍历

/**
 * @param {string} queryIP
 * @return {string}
 */
function validIPAddress(queryIP) {
  const ipv4List = queryIP.split('.')
  if (ipv4List.length === 4) {
    for (const i of ipv4List) {
      if (String(i * 1) !== i || Number(i) > 255) {
        return 'Neither'
      }
    }
    return 'IPv4'
  }
  const ipv6List = queryIP.split(':')
  if (ipv6List.length === 8) {
    for (const i of ipv6List) {
      const reg = /^[0-9a-f]{1,4}$/i
      if (!reg.test(i) || isNaN(Number.parseInt(i, 16))) {
        return 'Neither'
      }
    }
    return 'IPv6'
  }
  return 'Neither'
}