Created
September 19, 2019 22:46
-
-
Save CosmicPangolin/d4b79ae1ca956e3c5334abc2f2d8289a to your computer and use it in GitHub Desktop.
Alex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
fn binary_gap_length(mut x: u32) -> u32 { | |
let instant = Instant::now(); | |
let mut index:u32 = 0; | |
let mut gap_length:u32 = 0; | |
x = x >> x.trailing_zeros(); | |
while x != 0 { | |
if x & 1 == 1 { | |
//println!("1 end, {}", format!("{:b}", x)); | |
index = 0; | |
x = x>>1; | |
} else { | |
// println!("0 end, {}", format!("{:b}", x)); | |
index += 1; | |
gap_length = std::cmp::max(gap_length, index); | |
x = x>>1; | |
} | |
} | |
println!("{:?}", instant.elapsed()); | |
return gap_length; | |
} | |
//1+1 | |
//println!("now recursive"); | |
//println!("{}", problem_one(52823)); | |
fn problem_one(mut x: u32) -> u32 { | |
let instant = Instant::now(); | |
x = x >> x.trailing_zeros(); | |
let y = binary_gap_length_recursive(x, 0 , 0); | |
println!("{:?}", instant.elapsed()); | |
return y; | |
} | |
fn binary_gap_length_recursive(mut x: u32, mut max: u32, mut current: u32) -> u32 { | |
if x == 0 { | |
return max; | |
} else if x & 1 == 1 { | |
// println!("{:b}", x); | |
return binary_gap_length_recursive(x >> 1, max, 0); | |
} else { | |
// println!("adding 1 {:b}", x); | |
return binary_gap_length_recursive(x >> 1, std::cmp::max(current + 1, max), current + 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment