Day 5: Counting Bits


Today I was reading about Ownership and how Rust manages memory. I do not think I can do a better job than the Rust book and honestly, I missed coding so instead of writing about that I decided to take a break and go on Code Wars to tackle the counting bits problem in Rust instead.

Today’s problem is to count the number of bits in the binary form of a number. I got a solution that works, but because I know very little Rust at the moment I do not doubt that this will not be the ideal solution. But it’s my first Rust solution so I’m happy with it.

The Problem

We need a function that given an unsigned i64 returns the number of ones in the binary representation of the number.

Example

4 => 100 => 1
1234 => 10011010010 => 5

My Solution

fn count_bits(n: i64) -> u32 { let binary = format!("{:b}", n); let mut count: u32 = 0; for char in binary.chars() { if char == '1' { count += 1; } } count }
Code language: Rust (rust)

I don’t know all or any for that matter of the special methods available yet so I brute forced it.
My solution used the format macro to convert to a binary string, then loop over each character in the string incrementing a counter as a 1 is encountered.

I had problems remembering that semi-colons are required but the error messages were extremely helpful.

Other Peoples Solutions

After submission, I took a look at solutions by other people, and as I said there was definitely a better solution. Two of my favorites are.

fn count_bits(n: i64) -> u32 { n.count_ones() }
Code language: Rust (rust)

and

fn count_bits(n: i64) -> u32 { format!("{:b}", n).matches('1').count() as u32 }
Code language: Rust (rust)

I thought match could be used here but I haven’t read up on it yet, it’s two or three chapters from where I am. I am surprised however that there is a count_ones function, I did not expect that.

Since this is a short solution, this will be a short post. Do you know a better way to solve this problem in Rust? Let me know on Twitter @phoexer and happy coding.


Leave a Reply

Your email address will not be published.