🐡

CodilityをRustで解く

に公開

記録用

Lesson1 Iterations

https://app.codility.com/programmers/lessons/1-iterations/binary_gap/

Rust

もう少しシンプルに書けるかも

use std::cmp::{max};

fn sol1(n:i32) -> i32{ 
    let mut max_gap= 0;
    let mut gap =0;
    let mut i = 0;
    let mut in_gap = false;

    while n >= (1 << i){
        if (n & (1 << i) )== 0 {
                gap += 1;
        }
        else {
            if in_gap == false{
                in_gap = true;
            }
            else{
                max_gap = max(max_gap, gap);
            }
            gap = 0;
        }
        
        i += 1;
    };
    max_gap
    
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_sol1(){
        assert_eq!(2,sol1(9));
        assert_eq!(0,sol1(64));
    }
}

Discussion