题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
package main
import (
"fmt"
"strings"
"strconv"
)
func isValidIP(ip string) bool {
ipSegments := strings.Split(ip, ".")
if len(ipSegments) != 4 {
return false
}
for _, ipSegment := range ipSegments {
if len(ipSegment) > 1 && (ipSegment[0] == '0' || ipSegment[0] == '+') {
return false
}
ipSegmentNumber, err := strconv.Atoi(ipSegment)
if err != nil {
return false
}
if ipSegmentNumber < 0 || ipSegmentNumber > 255 {
return false
}
}
return true
}
func main() {
var ip string
fmt.Scan(&ip)
if !isValidIP(ip) {
fmt.Println("NO")
} else {
fmt.Println("YES")
}
}
// 本题输入一行字符串,所以采用:fmt.Scan(&ip)
