LeetCode - Strings - 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"

Example 3:

Input: n = 123456789
Output: "123.456.789"


class Solution {
    public String thousandSeparator(int n) {
        if(n<1000) return String.valueOf(n);
        else{
            String output = "";
            String n_str = String.valueOf(n);
            int counter = 0;
            for(int i=n_str.length()-1;i>=0;i--){
               counter++; 
               if(counter%3 == 0 && counter != 0 && counter != n_str.length()){
                   output = "."+n_str.charAt(i)+output;
               }else{
                    output = n_str.charAt(i)+output;    
               }
            }
            return output;
        }
    }
}

Recent Updates

Recent updates on DevOpsPal

Social

Follow us of social for latest updates.

DevOps Hub

Links to get started.