Last active
August 29, 2015 14:19
-
-
Save kirushik/b901d66506c617693bfb to your computer and use it in GitHub Desktop.
Binary palindromes in Rust
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 bin_reverse(n_orig: u32) -> u32 { | |
let mut n = n_orig; | |
n = ((n & 0xFFFF0000) >> 16) | ((n & 0x0000FFFF) << 16 ); | |
n = ((n & 0xFF00FF00) >> 8 ) | ((n & 0x00FF00FF) << 8 ); | |
n = ((n & 0xF0F0F0F0) >> 4 ) | ((n & 0x0F0F0F0F) << 4 ); | |
n = ((n & 0xCCCCCCCC) >> 2 ) | ((n & 0x33333333) << 2 ); | |
n = ((n & 0xAAAAAAAA) >> 1 ) | ((n & 0x55555555) << 1 ); | |
n | |
} | |
fn is_palindrome(n: u32) -> bool { | |
n == bin_reverse(n) >> n.leading_zeros() | |
} | |
fn main() { | |
let res: Vec<_> = (1900..2100).filter(|&n| is_palindrome(n)).collect(); | |
println!("{:?}", res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment