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

整数与IP地址间的转换

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

package main

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

func ip2number(s string) int {
    var bits [32]int
    var idx int

    ipSegment := strings.Split(s, ".")
    for _, segment := range ipSegment {
        var bit [8]int
        segmentIdx := 7
        number, _ := strconv.Atoi(segment)
        for number > 0 {
            bit[segmentIdx] = number % 2
            number /= 2
            segmentIdx--
        }

        for i:=0; i<8; i++ {
            bits[idx] = bit[i]
            idx++
        }
    }

    var sum int
    var powIdx int
    for i:=31; i>=0; i-- {
        sum += bits[i] * int(math.Pow(float64(2.0), float64(powIdx)))
        powIdx++
    }

    return sum
}

func number2ip(n int) string {
    var bits [32]int
    idx := 31

    for n > 0 {
        bits[idx] = n % 2
        n /= 2
        idx--
    }

    var ipSegment []int
    for i:=0; i<32; i=i+8 {
        segment := bits[i:i+8]
        var sum int
        var powIdx int
        for j:=7; j>=0; j-- {
            sum += segment[j] * int(math.Pow(float64(2.0), float64(powIdx)))
            powIdx++
        }
        ipSegment = append(ipSegment, sum)
    }

    return fmt.Sprintf("%d.%d.%d.%d", ipSegment[0], ipSegment[1], ipSegment[2], ipSegment[3])
}

func main() {
    var ip string
    var n int

    fmt.Scan(&ip, &n)

    fmt.Println(ip2number(ip))
    fmt.Println(number2ip(n))
}
// 本题输入为两行,所以采用:fmt.Scan(&ip, &n)

全部评论

相关推荐

牛客410815733号:这是什么电影查看图片
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务