题解 | #水仙花数#
水仙花数
https://www.nowcoder.com/practice/dc943274e8254a9eb074298fb2084703
use std::io::{self, *};
fn main() {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let ll = line.unwrap();
let numbers: Vec<&str> = ll.split(" ").collect();
let m: u32 = numbers[0].trim().parse::<u32>().unwrap_or(0);
let n: u32 = numbers[1].trim().parse::<u32>().unwrap_or(0);
let mut count = 0;
for number in m..=n {
if is_narcissistic_number(number) {
print!("{} ", number);
count += 1;
}
}
if count == 0 {
print!("no");
}
println!();
}
}
/// # 功能
/// 判断是否是水仙花数
/// # 参数
/// * `num` - 需要判断的数
/// # 返回值
/// 返回一个布尔值,true/false
/// # 示例
/// ```
/// let result = is_narcissistic_number(153); //判断整数153是否是水仙花数
/// assert_eq!(result, true); //检查函数输出结果是否正确
/// //1^3+5^3+3^3=153
/// ```
/// # 备注
/// 水仙花数的定义:一个三位数,它的各位数字的立方和等于其本身。
fn is_narcissistic_number(num: u32) -> bool {
let a = num / 100; //百位数
let b = (num / 10) % 10; //十位数
let c = num % 10; //个位数
(a.pow(3) + b.pow(3) + c.pow(3)) == num
}
查看7道真题和解析