题解 | 超级圣诞树
超级圣诞树
https://www.nowcoder.com/practice/470d26c9a73e4e17be8cc45cac843423
use std::io;
fn main() {
// 获取用户输入的圣诞树高度
let mut input = String::new();
while let Ok(_) = io::stdin().read_line(&mut input) {
let h: usize = match input.trim().parse() {
Ok(num) => num,
Err(_) => {
break;
}
};
// 初始化树枝部分
let mut branches = vec![
String::from("*"),
String::from("* *"),
String::from("* * *"),
];
// width 表示树枝的最宽的宽度
let width = 3 * 2_usize.pow(h as u32 - 1) + 3 * 2_usize.pow(h as u32 - 1) - 1;
// 迭代获得最终的树枝,用向量存储
for _ in 1..h {
let length = branches.len();
for i in 0..length {
// 左右对称,增加中间的空格
let middle_spaces = " ".repeat(2 * length - 1 - 2 * i);
branches.push(format!("{}{}{}", branches[i], middle_spaces, branches[i]));
}
}
// 输出树枝,居中对齐
for line in &branches {
println!("{:^width$}", line, width = width);
}
// 输出树干,居中对齐
for _ in 0..h {
println!("{:^width$}", "*", width = width);
}
// 清空输入缓冲区
input.clear();
}
}
#rust#