Similar Problems

Similar Problems not available

Thousand Separator - Leetcode Solution

Companies:

LeetCode:  Thousand Separator Leetcode Solution

Difficulty: Easy

Topics: string  

Problem statement:

Given an integer n, add a thousand separator at every three digits.

Example 1:

Input: n = 987 Output: "987"

Example 2:

Input: n = 1234 Output: "1,234"

Example 3:

Input: n = 123456789 Output: "123,456,789"

Solution:

Approach:

  • Convert the integer to a string.
  • Traverse the string from the end and insert a comma after every 3 characters.
  • Return the modified string.

Algorithm:

  • Convert the integer n to a string.

  • Initialize a variable res as an empty string to hold the result.

  • Initialize a variable count to keep track of the number of characters. Set it to 0.

  • Traverse the string from end to start.

  • If count is divisible by 3 and not zero, prepend a comma to res.

  • Append the current character to res.

  • Increment count.

  • Return the reverse of res.

Code:

The code for the above approach is as follows:

class Solution: def thousandSeparator(self, n: int) -> str: # convert the integer to a string s = str(n) # initialize variables res = "" count = 0 # traverse the string from end to start for i in range(len(s)-1, -1, -1): # prepend a comma after every 3 characters if count % 3 == 0 and count != 0: res = res + "," # append the current character res = res + s[i] count = count + 1 # return the reversed string return res[::-1]

Time Complexity:

The time complexity of the above approach is O(n), where n is the number of digits in the input integer.

Thousand Separator Solution Code

1