Thousand Separator
In Python, you can solve this problem using the format
function with specific formatting rules.
Here’s how to implement it:
|
|
The format
function is used here with :,
as the format specifier, which adds a comma as the thousands separator. We then use the replace
function to replace every comma with a dot.
The code reads an integer n
and transforms it into a string with dots as the thousands separators. This method ensures that the original number remains unchanged while the output string reflects the requirement. The formatting is done from right to left, grouping every three digits together and placing a dot before each group. The output is a string representation of the original number with the correct separators.
|
|
The C++ function thousandSeparator
takes an integer n
and returns a string that represents n
with commas inserted every three digits from the right.
Here’s how the function works:
It starts by converting the input integer
n
to a strings
using theto_string
function. It also initializes an empty stringres
to store the result.It then iterates over each character in the string
s
. For each indexi
, it checks whetheri
is greater than 0 and(s.size() - i) % 3
equals 0. The condition(s.size() - i) % 3 == 0
is true wheni
is three positions away from the end of the strings
.If the condition is true, it appends a dot to
res
.It then appends the character at index
i
ofs
tores
.Finally, it returns
res
, which is the string representation ofn
with a dot inserted every three digits from the right.
This function effectively formats the string representation of n
in a single pass, resulting in a time complexity of O(log n), where n is the input integer. The space complexity is also O(log n), as it creates a string of size proportional to the number of digits in n
.
The code is in C++, and it uses a loop to iterate through the string representation of the number. The if
condition inside the loop checks whether we’ve moved three characters forward in the string, and if so, it adds a dot to the result.
Python code:
|
|
In this code, the input integer is first converted to a string. Then, for every character in the string, if the index is not zero and the remaining length of the string is a multiple of three, a dot is appended to the result string. After checking the condition, the character is added to the result string. This process continues until all characters from the input string have been processed. Finally, the resulting string is returned.