Given an integer
n
, add a dot (".") as the thousands separator and return it in string format.Example 1:
Input: n = 1234
Output: "1.234"
Approach
Java
public class ThousandSeparator {public static void main(String[] args) {int n = 1234;System.out.println(thousandSeparator(n));}static String thousandSeparator(int n) {String s = String.valueOf(n);int len = s.length();int i = len - 1;String str = "";while (true) {int cnt = 0;while (i >= 0) {str = s.charAt(i) + str;cnt++;i--;if (cnt == 3)break;}if (i >= 0)str = '.' + str;if (i < 0)break;}return str;}}
C++
#include <bits/stdc++.h>using namespace std;string thousandSeparator(int n){string s = to_string(n);int len = s.size();int i = len - 1;string str = "";while (true){int cnt = 0;while (i >= 0){str = s[i] + str;cnt++;i--;if (cnt == 3)break;}if (i >= 0)str = '.' + str;if (i < 0)break;}return str;}int main(){int n = 1234;cout << thousandSeparator(n);return 0;}
No comments:
Post a Comment