Skip to content

Latest commit

 

History

History
77 lines (66 loc) · 1.37 KB

1556. Thousand Separator.md

File metadata and controls

77 lines (66 loc) · 1.37 KB

the first one in Biweekly Contest 33.


Difficulty : Easy

Related Topics : String


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"

Example 4:

Input: n = 0
Output: "0"

Constraints:

  • 0 <= n < 2^31

Solution

  • mine
    • Java
      • Runtime: 0 ms, faster than 100.00%, Memory Usage: 37 MB, less than 83.92% of Java online submissions
        // O(N)time
        // O(N)space
        public String thousandSeparator(int n) {
            if(n == 0) return "0";
            LinkedList<Object> list = new LinkedList<>();
            int count = 0;
            while(n > 0){
                if(count==3){
                    list.addFirst(".");
                    count = 0;
                }
                count++;
                list.addFirst(n % 10);
                n /= 10;
            }
            StringBuilder res = new StringBuilder();
            while(!list.isEmpty()){
                res.append(list.removeFirst());
            }
            return res.toString();
        }