while trying to solve a leetcode problem in rust !
there was a arbitary condition where iam unable to diagnose why the code throws wrong output for a specific test case !

here is the link for that question

that specific test case

impl Solution {
pub fn chalk_replacer(chalk: Vec<i32>, k: i32) -> i32 {
// here (K) is the actual value we have to find the last elem remainder
let sum : i32 = chalk.iter().sum(); //gather the sum
let mut remainder = k % sum ; // find the remainder from the (k)
// iterate with curr elem & index in the vector compound type
for (idx , &elem) in chalk.iter().enumerate() {
// if the curr elem is greater than the remainder return this index
if elem > remainder { return idx as i32;}
// reduce the curr elem from remainder each time in loop
remainder -= elem;
}
// if something went wrong then return -1 (though never be returned actually)
return -1;
}
}

Trigger warning: This question is a lot like asking someone to do their homework. For that reason, I am not going to give you a direct answer. But I will comment that you don't need to iterate the vector apart from the initial summation to solve this challenge.

I expect (but have not verified) that all test inputs will not overflow i32 when summed, but that is a possibility that you should consider.

This doesn't seem to have anything to do with casting, although you can check out the corresponding chapter from The Rust Reference if you want a formal explanation of how casting works.

I copied your code into the playground and added print statements so we would see something similar to the example explanations, however the actual "explanation" is completely different.

-------
Input: chalk = [5, 1, 5], k = 22
Explanation:
Student number 0 does not have enough chalk, so they will have to replace it.
Output: Some(0)
-------
Input: chalk = [3, 4, 1, 2], k = 25
Explanation:
- Student number 0 uses 3 chalk so k = 2.
Student number 1 does not have enough chalk, so they will have to replace it.
Output: Some(1)

Try solving the examples on paper and see where it differs from your code. I think you might have a logic flaw somewhere.

yeah ..you are right ! ..yikes ..my type handling understanding in rust is something which is yet to be developed .. since ,,in iam badly used with C++ type system ...
but anyways ...I found the solution ...

pub fn chalk_replacer(chalk: Vec<i32>, k: i32) -> i32 {
let sum : usize = chalk.iter().fold(0, |acc, &x| acc + (x as usize));
println!("sum: {:?}", sum);
let mut remainder = ((k as usize) % (sum));
println!("rem: {:?}", remainder);
for (idx , &elem) in chalk.iter().enumerate() {
if elem as usize > remainder { return idx as i32;}
remainder -= (elem as usize);
}
return -1;