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

整数与IP地址间的转换

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

思路: 其实这题就是考察位运算,只需要使用32位无符号整数来进行表达即可,稍稍注意一下位运算的优先级。
下面代码也可舍弃中间变量a、b、c、d,但这样不利于读清楚。

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

fn main() {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let ll = line.unwrap();
        if ll.contains(".") {
            let numbers: Vec<&str> = ll.split(".").collect();
            let a = numbers[0].trim().parse::<u32>().unwrap_or(0);
            let b = numbers[1].trim().parse::<u32>().unwrap_or(0);
            let c = numbers[2].trim().parse::<u32>().unwrap_or(0);
            let d = numbers[3].trim().parse::<u32>().unwrap_or(0);
            println!("{}",(a << 24) + (b << 16) + (c << 8) + d);
        } else {
            let n = ll.trim().parse::<u32>().unwrap_or(0);
            let a = (n & 0b11111111000000000000000000000000u32) >>24;
            let b = (n & 0b00000000111111110000000000000000u32) >>16;
            let c = (n & 0b00000000000000001111111100000000u32) >>8;
            let d = n & 0b00000000000000000000000011111111u32;
            println!("{}.{}.{}.{}",a,b,c,d);
        }
    }
}
用 Rust 刷华为机试HJ 文章被收录于专栏

用 Rust 刷 HJ100 题,只需要懂基础 Rust 语法就能看懂

全部评论
该牛油正在参与牛客写题解薅羊毛的活动,牛币,周边,京东卡超多奖品放送,活动进入倒计时!快来捡漏啦https://www.nowcoder.com/discuss/888949?source_id=profile_create_nctrack&channel=-1
点赞 回复 分享
发布于 2022-04-27 11:47

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务