Solution:read
#include <iostream>
#include <string>
using namespace std;
/**
******************************************************************************
*
* Counts the minimum number of coins to add up to sum.
*
* @param argc
* @param argv
*
* @return int
*
******************************************************************************
*/
int main (int argc, char *argv[])
{
enum
{
QUARTER = 25,
DIME = 10,
NICKEL = 5,
PENNY = 1
};
string amount, amountSaved;
int ones = 0, tenths = 0, dollars = 0;
cout << "This program calculates the minimum number of coins to make change in coins" << endl;
cout << "Enter a $ amount (e.g. 1.2 for one dollar 20 cents):$ ";
cin >> amount;
dollars = atoi(&amount[0]);
// Checks for a decimal point
size_t pos = amount.find(".");
if (amount.npos != pos)
{
size_t trail = amount.size() - 1; // excludes decimal point
if (trail > 2)
{
amount.erase(pos+3); // erase chars after 2 decimal digits
}
amountSaved = amount; // save a copy
ones = atoi(&amount[pos+2]);
amount[pos+2] = '\0';
tenths = atoi(&amount[pos+1]);
}
unsigned int total = static_cast<unsigned int>(dollars * 100 + tenths * 10 + ones);
int denom[] = {QUARTER, DIME, NICKEL, PENNY};
const int nDenom = sizeof(denom) / sizeof(int);
int count[nDenom] = {0, 0, 0, 0};
int coins = 0;
// Using Greedy algorithm
while (total)
{
if (total >= denom[coins])
{
count[coins]++;
total -= denom[coins];
}
else
{
coins++;
}
}
cout << "Number of coins for $ " << amountSaved << " is:\n";
cout << count[0] << " quarters" << endl;
cout << count[1] << " dimes" << endl;
cout << count[2] << " nickels" << endl;
cout << count[3] << " pennies" << endl;
return 0;
}
// Original solution provided by Jeff Fore.
hide solution
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.