题解 | 超级圣诞树

超级圣诞树

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#
全部评论

相关推荐

秋盈丶:后续:我在宿舍群里和大学同学分享了这事儿,我好兄弟气不过把他挂到某脉上了,10w+阅读量几百条评论,直接干成精品贴子,爽
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务