Leetcode 1556. Thousand Separator
You are given an integer n
. You need to 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"
Q: Can the input number be negative?
A: No, the input n
is always a non-negative integer.
Q: Is there a maximum limit to the value of n
?
A: n
is within the range [0, 2^31 - 1]
.
public class ThousandSeparator {
public static void main(String[] args) {
int n = 1234567;
System.out.println(thousandSeparator(n)); // Should return "1.234.567"
}
public static String thousandSeparator(int n) {
// Convert number to string
String numStr = Integer.toString(n);
StringBuilder result = new StringBuilder();
// Counter to keep track of every three characters
int count = 0;
// Iterate from the end of the string towards the start
for (int i = numStr.length() - 1; i >= 0; i--) {
result.append(numStr.charAt(i));
count++;
// Add dot after every three characters
if (count == 3 && i > 0) {
result.append('.');
count = 0;
}
}
// Reverse the result to get the correct order
return result.reverse().toString();
}
}
n
is the number of digits in the integer. We have to iterate through the string representation of the number once.This approach ensures that we correctly handle numbers of any length and format them with dots as the thousands separators.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?