Skip to content

Commit

Permalink
lc: Add number of 1 bits
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Nov 29, 2023
1 parent 5145754 commit 5d71cbb
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions leetcode/191.number_of_1_bits/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc_191_number_of_1_bits"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
62 changes: 62 additions & 0 deletions leetcode/191.number_of_1_bits/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) 2023 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be
// found in the LICENSE file.

//! Problem: [Number of 1 bits](https://leetcode.com/problems/number-of-1-bits)
fn solution1(n: u32) -> i32 {
let mut n = n;
let mut count = 0;
while n != 0 {
count += n % 2;
n /= 2;
}
count as i32
}

fn solution2(n: u32) -> i32 {
n.count_ones() as i32
}

fn main() {
let n = 0b00000000000000000000000000001011;
assert_eq!(solution1(n), 3);

let n = 0b00000000000000000000000010000000;
assert_eq!(solution1(n), 1);

let n = 0b11111111111111111111111111111101;
assert_eq!(solution1(n), 31);

let n = 0b11111111111111111111111111111101;
assert_eq!(solution2(n), 31);
}

#[cfg(test)]
mod tests {
use super::{solution1, solution2};

#[test]
fn test_solution1() {
let n = 0b00000000000000000000000000001011;
assert_eq!(solution1(n), 3);

let n = 0b00000000000000000000000010000000;
assert_eq!(solution1(n), 1);

let n = 0b11111111111111111111111111111101;
assert_eq!(solution1(n), 31);
}

#[test]
fn test_solution2() {
let n = 0b00000000000000000000000000001011;
assert_eq!(solution2(n), 3);

let n = 0b00000000000000000000000010000000;
assert_eq!(solution2(n), 1);

let n = 0b11111111111111111111111111111101;
assert_eq!(solution2(n), 31);
}
}

0 comments on commit 5d71cbb

Please sign in to comment.