LeetCode 1556: Thousand Separator Solution
Master LeetCode problem 1556 (Thousand Separator), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1556. Thousand Separator
Problem Explanation
Explanation:
To solve this problem, we can convert the integer to a string and then insert a dot character every 3 digits from the right. We need to handle the edge case where the number of digits is not divisible by 3.
- Convert the given integer
nto a string. - Initialize an empty string
result. - Iterate over the characters in the string representation of
nfrom right to left.- Prepend the current character to
result. - If the current index is not the last character and the distance from the current index to the end of the string is divisible by 3, insert a dot character at the beginning of
result.
- Prepend the current character to
- Return the final
resultstring.
Time Complexity:
The time complexity of this approach is O(log(n)), where n is the input integer.
Space Complexity:
The space complexity is O(log(n)) to store the string representation of the integer.
:
Solution Code
class Solution {
public String thousandSeparator(int n) {
String str = String.valueOf(n);
StringBuilder result = new StringBuilder();
for (int i = str.length() - 1, count = 0; i >= 0; i--) {
result.insert(0, str.charAt(i));
count++;
if (i != 0 && count % 3 == 0) {
result.insert(0, '.');
}
}
return result.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1556 (Thousand Separator)?
This page provides optimized solutions for LeetCode problem 1556 (Thousand Separator) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1556 (Thousand Separator)?
The time complexity for LeetCode 1556 (Thousand Separator) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1556 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1556 in Java, C++, or Python.