Missing Number Via Iterator Sum
Derive the missing number from the full range sum minus the iterator sum, then cross-check with an xor pass where paired indexes and values cancel out.
Code
fn missing_number(numbers: &[u64]) -> u64 {
let n = numbers.len() as u64;
// missing number via iterator sum: full range minus actual values
(0..=n).sum::<u64>() - numbers.iter().sum::<u64>()
}
// 用 xor 交叉验证:下标与值成对出现互相抵消,剩下的是缺失值
fn missing_number_xor(numbers: &[u64]) -> u64 {
let n = numbers.len() as u64;
let mut acc = 0u64;
for (i, value) in numbers.iter().enumerate() {
acc ^= (i as u64) ^ value;
}
acc ^ n
}
fn main() {
for numbers in [[0u64, 1, 2, 4, 5], [3, 0, 1, 5, 2]] {
assert_eq!(missing_number(&numbers), missing_number_xor(&numbers));
println!("missing number: {}", missing_number(&numbers));
}
}Missing Number Via Iterator Sum: the mechanics
All of the logic lives in the functions missing_number, missing_number_xor and main.
for (i, value) in numbers.iter().enumerate() is where each item gets processed.
What to watch for
- What the toolchain ships is sufficient; nothing extra required.
Applying it
Signature: fn missing_number(numbers: &[u64]) -> u64
Each run prints the following labels: missing number:.
main sequences missing_number and missing_number_xor; executing the file runs that flow once.
Statements that matter
fn missing_number_xor(numbers: &[u64]) -> u64 {
let n = numbers.len() as u64;
let mut acc = 0u64;
for (i, value) in numbers.iter().enumerate() {
acc ^= (i as u64) ^ value;
}
acc ^ n
}
fn missing_number(numbers: &[u64]) -> u64 {
let n = numbers.len() as u64;
// missing number via iterator sum: full range minus actual values
(0..=n).sum::<u64>() - numbers.iter().sum::<u64>()
}
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.
FAQ
- What does Missing Number Via Iterator Sum print when run?
- Invoke the file as-is — the `missing number:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.