1556. Thousand Separator LeetCode Solution
In this guide, you will get 1556. Thousand Separator LeetCode Solution with the best time and space complexity. The solution to Thousand Separator problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Thousand Separator solution in C++
- Thousand Separator solution in Java
- Thousand Separator solution in Python
- Additional Resources
Problem Statement of Thousand Separator
Given an integer n, add a dot (“.”) as the thousands separator and return it in string format.
Example 1:
Input: n = 987
Output: “987”
Example 2:
Input: n = 1234
Output: “1.234”
Constraints:
0 <= n <= 231 – 1
Complexity Analysis
- Time Complexity: O(\log n)
- Space Complexity: O(\log n)
1556. Thousand Separator LeetCode Solution in C++
class Solution {
public:
string thousandSeparator(int n) {
const string s = to_string(n);
string ans;
for (int i = 0; i < s.length(); ++i) {
if (i > 0 && (s.length() - i) % 3 == 0)
ans += '.';
ans += s[i];
}
return ans;
}
};
/* code provided by PROGIEZ */
1556. Thousand Separator LeetCode Solution in Java
class Solution {
public String thousandSeparator(int n) {
final String s = Integer.toString(n);
StringBuilder ans = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
if (i > 0 && (s.length() - i) % 3 == 0)
ans.append('.');
ans.append(s.charAt(i));
}
return ans.toString();
}
}
// code provided by PROGIEZ
1556. Thousand Separator LeetCode Solution in Python
class Solution:
def thousandSeparator(self, n: int) -> str:
return f'{n:,}'.replace(',', '.')
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.