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.
Input: n = 987 Output: "987"
Input: n = 1234 Output: "1.234"
Input: n = 123456789 Output: "123.456.789"
Input: n = 0 Output: "0"
0 <= n < 2^31
- 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(); }
- Java