题解 | #判断两个IP是否属于同一子网#

判断两个IP是否属于同一子网

https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218

use std::io::{self, *};

struct Ip {
    n: u32
}

impl Ip {
    fn is_valid(&mut self, i: &str) -> bool {
        let t = i.split(".").map(|i| { i.parse::<u32>().unwrap_or(256) }).collect::<Vec<u32>>();
        if t.len() != 4 || t.iter().any(|i| { !((0..256).contains(i)) }) { return false }
        self.n = (t[0] << 24) + (t[1] << 16) + (t[2] << 8) + t[3];
        true
    }
    fn is_valid_mask(&self) -> bool {
        (self.n << self.n.count_ones()) == 0
    }
    fn  in_same_subnet(&self, other: &Ip, mask: &Ip) -> bool {
        return (self.n & mask.n) == (other.n & mask.n)
    }

}

fn main() {
    let stdin = io::stdin();
    let lines = stdin.lock().lines().map(|line| {
        line.unwrap().trim().to_string()
    }).collect::<Vec<String>>();
    for i in 0..(lines.len() / 3) {
        let mut mask = Ip {n:0}; 
        let mut ip1 = Ip {n:0};
        let mut ip2 = Ip {n:0};
        if !mask.is_valid(&lines[i * 3]) || !ip1.is_valid(&lines[i * 3 + 1]) || !ip2.is_valid(&lines[i * 3 + 2]) {
            println!("1");
        } else if !mask.is_valid_mask() {
            println!("1");
        } else if ip1.in_same_subnet(&ip2, &mask) {
            println!("0");
        } else {
            println!("2");
        }
    }
}

全部评论

相关推荐

路过的咸蛋超人也想拿offer:你是我见过最美的牛客女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务