我想判断一个整数是否是2的幂.我的标准方法是看log₂(x)
是否是一个整数值,但我没有找到优雅的方法来做到这一点.我的方法如下:
let x = 65;
let y = (x as f64).log(2.0);
// Compute the difference between y and the result of
// of truncating y by casting to int and back
let difference = y - (y as i64 as f64);
// This looks nice but matches on float values will be phased out
match difference {
0.0 => println!("{} is a power of 2", x),
_ => println!("{} is NO power of 2", x),
}
// This seems kind of clunky
if difference == 0.0 {
println!("{} is a power of 2", x);
} else {
println!("{} is NO power of 2", x);
}
Is there a builtin option in Rust to check if a float can be converted to an integer without truncation?
行为类似于:
42.0f64.is_int() // True/ Ok()
42.23f64.is_int() // False/ Err()
换句话说,一个方法/宏/等,它允许我判断通过强制转换为int是否会丢失信息(小数).
I already found that checking whether an integer is a power of 2 can be done efficiently with 100.