Skip to content

Instantly share code, notes, and snippets.

@sts10
Created April 11, 2019 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sts10/38aba7b301c6cece93be94ed4cd24222 to your computer and use it in GitHub Desktop.
Save sts10/38aba7b301c6cece93be94ed4cd24222 to your computer and use it in GitHub Desktop.
Playing with Digits kata
// https://www.codewars.com/kata/playing-with-digits/train/rust
// status: Getting a multiply overflow werror when I "Attempt"
fn dig_pow(n: i64, p: i32) -> i64 {
let digits: Vec<_> = n.to_string().chars().map(|d| d.to_digit(10).unwrap()).collect();
let mut sum: u64 = 0;
let mut i: u32 = 0;
for digit in digits {
let power = p as u32 + i;
println!("This digit is {}", digit);
println!("This power is {}", power);
let to_add: u64 = digit.pow(power).into();
println!("Calculated to_add as {}", to_add);
sum += to_add as u64;
println!("So sum is now {}", sum);
i = i + 1;
}
if sum % n as u64 == 0 {
return (sum / n as u64) as i64
} else {
-1
}
}
@seanlynch
Copy link

for digit: u64 in digits maybe?

@sts10
Copy link
Author

sts10 commented Apr 11, 2019

got it

fn dig_pow(n: i64, p: i32) -> i64 {
    let digits: Vec<_> = n.to_string().chars().map(|d| d).collect();

    
    let mut sum: u64 = 0;
    let mut i: u32 = 0;
    for digit in digits {
        let digit: u64 = digit.to_digit(10).unwrap().into();
        let power = p as u32 + i;
        println!("This digit is {}", digit);
        println!("This power is {}", power);
        let to_add: u64 = digit.pow(power).into();
        println!("Calculated to_add as {}", to_add);
        sum += to_add as u64;
        println!("So sum is now {}", sum);
        i = i + 1;
    }

    if sum % n as u64 == 0 {
      return (sum / n as u64) as i64
     } else {
      -1
     }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment