Counter game

  • + 0 comments

    Rust best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    fn counter_game(n: i64) -> String {
        //Time complexity: O(log(n))
        //Space complexity (ignoring input): O(1)
        let mut n = n;
        let mut count_turns = 0;
        while n > 1 {
            let n_is_power_2 = n & (n - 1) == 0;
            if n_is_power_2 {
                while n > 1 {
                    n = n >> 1;
                    count_turns += 1;
                }
            } else {
                let mut pow_2 = 1;
                while pow_2 * 2 < n {
                    pow_2 = pow_2 << 1;
                }
                n = n - pow_2;
                count_turns += 1;
            }
        }
    
        if count_turns % 2 == 0 {
            return String::from("Richard");
        } else {
            return String::from("Louise");
        }
    }