[炼手Rust]下一个完美平方数

270 阅读1分钟

Hi,大家好,这里是炼手Rust专栏,我是xiaoK,今天一起来看一个小问题:下一个完美平方数。

提问

一个数N如果开平方之后,是一个整数,那么它就是一个完美平方数,求该数下一个完美平方数。

例: 121 是一个完美平方数,因为它开根是 11,所以下一个就是 144。
625 --> 676
114 --> None
100 --> 121

模板:

fn find_next_square(sq: u64) -> Option<u64> {
   
}

分析

开根是整数,那么就看小数部分是不是 0 或者整数部分是不是自己即可。然后得到N+1再计算平方。

解决方案

pub fn find_next_square(sq: u64) -> Option<u64> {
    let root = (sq as f64).sqrt();
    (root.trunc() == root).then(|| (root as u64 + 1).pow(2))
}

Trick

  1. 进行平方计算的时候,使用sqrt方法,该方法需要一个f64类型,所以需要提前把u64转换成f64
  2. f64类型有一个trunc方法,返回一个浮点数的整数部分。见文档描述:
Returns the integer part of self. This means that non-integer numbers are always truncated towards zero.
This function always returns the precise result.
  1. rust中的bool类型可以使用then方法来执行后续代码,如果该bool类型为true,则执行then的闭包,如果为false,则返回None。见文档描述:
Returns Some(f()) if the bool is true, or None otherwise.