Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions bit_manipulation/count_bits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
def count_bits(n: int) -> int:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

"""
Count the number of set bits (1s) in the binary representation of a
non-negative integer.

Examples:
>>> count_bits(0)
0
>>> count_bits(1)
1
>>> count_bits(5) # 101
2
>>> count_bits(15) # 1111
4
>>> count_bits(16) # 10000
1
"""
if n < 0:
raise ValueError("Input must be non-negative")

count = 0
while n > 0:
count += n & 1
n >>= 1

return count


if __name__ == "__main__":
import doctest

doctest.testmod()
52 changes: 52 additions & 0 deletions strings/integer_to_roman.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
def integer_to_roman(n: int) -> str:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I will change the name and make it descriptive.Thanks for the review.

"""
Convert an integer to a Roman numeral.

Examples:
>>> integer_to_roman(1)
'I'
>>> integer_to_roman(4)
'IV'
>>> integer_to_roman(9)
'IX'
>>> integer_to_roman(58)
'LVIII'
>>> integer_to_roman(1994)
'MCMXCIV'
>>> integer_to_roman(0)
Traceback (most recent call last):
...
ValueError: number must be between 1 and 3999
"""
if not (1 <= n <= 3999):
raise ValueError("number must be between 1 and 3999")

symbols = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
]

result = []
for value, numeral in symbols:
while n >= value:
result.append(numeral)
n -= value

return "".join(result)


if __name__ == "__main__":
import doctest

doctest.testmod()