题解 | #整数与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 语法就能看懂