ilog10 Digit Count And checked_pow
Count decimal digits with ilog10 and probe powers with checked_pow, which answers None where plain multiplication would overflow.
Code
fn main() {
let n: u32 = 123_456;
// ilog10:十进制位数 = ilog10 + 1(对 0 调用会 panic)
println!("{} digits: {}", n, n.ilog10() + 1);
// ilog 接受任意底数:16 进制位的上界
println!("ilog(16): {}", n.ilog(16));
// checked_pow:溢出返回 None,不 panic、不回绕
let base: u32 = 3;
println!("3^20 = {:?}", base.checked_pow(20));
println!("3^21 = {:?}", base.checked_pow(21));
// 手数位数与 ilog10 互相印证
let mut rest = n;
let mut digits = 1;
while rest >= 10 {
rest /= 10;
digits += 1;
}
println!("loop digits {} == ilog10 + 1 {}", digits, n.ilog10() + 1);
// 位宽与十进制位数是两件事
println!("bits needed: {}", u32::BITS - n.leading_zeros());
}Digits, bits, and overflow answers
A single main drives all five checks.
Repetition is confined to while rest >= 10 — the rest of the file is straight-line.
Points of care
- ilog and checked_pow are primitive methods — nothing outside the language is required.
Applying it
The entry-point signature is fn main()
The demo output is labeled (ilog(16):, 3^20 =, 3^21 =); each label names the call that printed it.
The calls worth quoting
digits += 1;
Interactive Tools for This Topic
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- What does ilog10 Digit Count And checked_pow print when run?
- No setup needed: run the file and look for labeled lines like `ilog(16):`, `3^20 =`, `3^21 =` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.