Program to format a number with thousands separator in C/C++
Last Updated :
31 Oct, 2020
Given an integer N, the task is to print output of the given integer in international place value format and put commas at the appropriate place, from the right.
Examples
Input: N = 47634
Output: 47, 634
Input: N = 1000000
Output : 1, 000, 000
Approach: Follow the steps below to solve the problem:
- Convert the given integer N to its equivalent string.
- Iterate over the characters of the given string from the right to the left.
- After traversing every 3 characters, insert a ‘,’ separator.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string thousandSeparator( int n)
{
string ans = "" ;
string num = to_string(n);
int count = 0;
for ( int i = num.size() - 1;
i >= 0; i--) {
count++;
ans.push_back(num[i]);
if (count == 3) {
ans.push_back( ',' );
count = 0;
}
}
reverse(ans.begin(), ans.end());
if (ans.size() % 4 == 0) {
ans.erase(ans.begin());
}
return ans;
}
int main()
{
int N = 47634;
string s = thousandSeparator(N);
cout << s << endl;
}
|
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...