Created
December 27, 2020 11:52
-
-
Save transhapHigsn/85e85c298916bb6a833341f2e2bf31c2 to your computer and use it in GitHub Desktop.
Get number of set bits in a decimal number
This file contains hidden or 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
use std::io; | |
fn number_of_bits(num: u32) -> u32 { | |
let mut count = 0; | |
let mut copy_num = num; | |
while copy_num > 0 { | |
count += 1; | |
copy_num = copy_num & (copy_num - 1); | |
} | |
count | |
} | |
fn read_input() -> String { | |
let mut text = String::new(); | |
io::stdin().read_line(&mut text).unwrap(); | |
text | |
} | |
fn read_integer() -> u64 { | |
let input = read_input(); | |
let integer: u64 = input.trim().parse().unwrap(); | |
integer | |
} | |
fn main() { | |
println!("Enter number of test cases: "); | |
let cases = read_integer(); | |
let mut test_cases: u32 = cases as u32; | |
println!("Enter input for test case: "); | |
while test_cases > 0 { | |
let num: u32 = read_integer() as u32; | |
let no_of_bits = number_of_bits(num); | |
println!("Result: {}", no_of_bits); | |
test_cases -= 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment