题解 | #整数与IP地址间的转换#

整数与IP地址间的转换

https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
    for {
        var a string
        n , _ := fmt.Scan(&a)
        if n == 0 {
            break
        } else {
            ip := strings.Split(a, ".")
            if  len (ip) == 4 {
                 ip1, _ := strconv.Atoi(ip[0])
                 ip2, _ := strconv.Atoi(ip[1])
                 ip3, _ := strconv.Atoi(ip[2])
                 ip4, _ := strconv.Atoi(ip[3])
                 b := uint(ip1) << 24 | uint(ip2) << 16 | uint(ip3) << 8 | uint(ip4)
                 fmt.Println(b) 
            } else {
                ip1, _ := strconv.Atoi(a)
                ip2, _ := strconv.Atoi(a)
                ip3, _ := strconv.Atoi(a)
                ip4, _ := strconv.Atoi(a)
                c := strconv.Itoa((ip1>>24) & 255) + "." + strconv.Itoa((ip2>>16) & 255) + "." + strconv.Itoa((ip3>>8) & 255) + "." + strconv.Itoa((ip4) & 255)
                fmt.Println(c)
            }
        }
    }
}

全部评论

相关推荐

10-20 11:11
辽宁大学 营销
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务