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.
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
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.
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.
Today I am working on a summation problem made to look like building a tower out of cubic bricks. It’s fun to brute force sometimes.
Coming back to Rust code after a bit of a hiatus with a simple problem… The Two-sum problem. Finding numbers in an array. Yay, fun.
King Pinn: I Salute You. I’m driving halfway across the country and this song is on repeat. Rest in Peace Tonderai Makoni. You were awesome.
After a few weeks off I’m back to business. This is just an update post detailing plans for the rest of the year.
At last we finally have the great reveal, our mystery project was implementing RSA encryption in rust.