algoadvance

Leetcode 1556. Thousand Separator

Problem Statement

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"

Clarifying Questions

  1. Q: Can the input number be negative? A: No, the input n is always a non-negative integer.

  2. Q: Is there a maximum limit to the value of n? A: n is within the range [0, 2^31 - 1].

Strategy

  1. Convert the integer to its string representation.
  2. Initialize a result string and iterate backward from the end of the string.
  3. Maintain a counter to keep track of every three characters.
  4. Insert a dot every time you complete three characters.
  5. Return the final formatted string.

Code

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();
    }
}

Time Complexity

This approach ensures that we correctly handle numbers of any length and format them with dots as the thousands separators.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI