Skip to content

Instantly share code, notes, and snippets.

@CosmicPangolin
Created September 19, 2019 22:46
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 CosmicPangolin/d4b79ae1ca956e3c5334abc2f2d8289a to your computer and use it in GitHub Desktop.
Save CosmicPangolin/d4b79ae1ca956e3c5334abc2f2d8289a to your computer and use it in GitHub Desktop.
Alex
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