Skip to content

Commit da2db17

Browse files
authored
Update num_ones.md
1 parent 6881eb2 commit da2db17

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

docs/num_ones.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ fn count_bits(mut num: Int) -> Int:
88
num = num >> 1
99
return result
1010

11+
fn count_bits2(mut num: Int) -> Int:
12+
result = 0
13+
while num:
14+
result += num & 1
15+
num >>= 1
16+
return result
17+
1118
from testing import assert_equal
1219

1320
fn main() raises:
@@ -17,6 +24,12 @@ fn main() raises:
1724
assert_equal(1, count_bits(num))
1825
num = 2147483645
1926
assert_equal(30, count_bits(num))
27+
num = 11
28+
assert_equal(3, count_bits2(num))
29+
num = 128
30+
assert_equal(1, count_bits2(num))
31+
num = 2147483645
32+
assert_equal(30, count_bits2(num))
2033
```
2134

2235
[Soure](https://github.com/ratulb/mojo_programming/blob/main/codes/num_ones.mojo)

0 commit comments

Comments
 (0)