محتوى الدرس
#include <iostream>
#include <string>
using namespace std;
/*
Money Format
100 -> 100
1000 -> 1,000
100000 -> 100,000
1000000 -> 1,000,000
*/
string moneyFormat(int n)
{
string snum = to_string(n); // 100000
string result;
int count = 0;
for (int i = snum.size() - 1; i >= 0; i--) // [1]00000
{
result = snum[i] + result; // i = 0
// [Loop 1] 0 + ""
// [Loop 2] 0 + 0 + ""
// [Loop 3] 0 + 0 + 0 + ""
// [Loop 3] , + 0 + 0 + 0 + ""
// [Loop 4] 0 + , + 0 + 0 + 0 + ""
// [Loop 5] 0 + 0 + , + 0 + 0 + 0 + ""
// [Loop 6] 1 + 0 + 0 + , + 0 + 0 + 0 + ""
// Last Result -> 100,000
count++; // 6
if (count % 3 == 0 && i != 0)
{
result = "," + result;
}
}
return result;
}
int main()
{
cout << moneyFormat(100) << endl;
cout << moneyFormat(1000) << endl;
cout << moneyFormat(10000) << endl;
cout << moneyFormat(100000) << endl;
cout << moneyFormat(1000000) << endl;
cout << moneyFormat(10000000) << endl;
cout << moneyFormat(100000000) << endl;
cout << moneyFormat(1000000000) << endl;
return 0;
}