C和指针第七章written_amount C++实现

来源:互联网 发布:mac新系统 编辑:程序博客网 时间:2024/05/17 22:46
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <string>
using namespace std;
typedef vector<unsigned int> UIntVector;


static char *digits[] = {
    "", "ONE ", "TWO ", "THREE ", "FOUR ", "FIVE ", "SIX ", "SEVEN ",  
    "EIGHT ", "NINE ", "TEN ", "ELEVEN ", "TWELVE ", "THIRTEEN ",  
    "FOURTEEN ", "FIFTEEN ", "SEXTEEN ", "SEVENTEEN ", "EIGHTEEN ",  
    "NINETEEN "
};


static char *tens[] = {
    "", "", "TWENTY ", "THIRTY ", "FORTY ", "FIFTY ", "SIXTY ", "SEVENTY ",  
    "EIGHTY ", "NINETY "
};


static char *magnitudes[] = {
    "", "THOUSAND ", "MILLION ","BILLION "
};


void print_hundred(unsigned int hundreds, string &buffer)
{
    if (hundreds > 99)
    {
        buffer.append(digits[hundreds/100]);
        buffer.append("HUNDRED ");
    }
    hundreds %= 100;
    if (hundreds > 19)
    {
        buffer.append(tens[hundreds/10]);
        hundreds %= 10;
        buffer.append(digits[hundreds]);
    }
    else
    {
        buffer.append(digits[hundreds]);
    }
}


void written_amount(unsigned int amount, string &buffer)
{
    if (amount == 0)
    {
        buffer.append("ZERO");
        return;
    }
    UIntVector blocks;
    blocks.reserve(4); // the greatest unsigned integer can be divided into 4 blocks
    unsigned int value = amount;
    while (value > 0)
    {
        unsigned int tmp = value%1000;
        blocks.push_back(tmp);
        value /= 1000;
    }
    size_t blocks_size = blocks.size();
    for(UIntVector::reverse_iterator rIt = blocks.rbegin(); rIt != blocks.rend(); ++rIt, blocks_size--)
    {
        if (*rIt > 0)
        {
            print_hundred(*rIt, buffer);
            buffer.append(magnitudes[blocks_size-1]);
        }
    }
}




int _tmain(int argc, _TCHAR* argv[])
{
    unsigned int myAmount = 16312;
    std::string buffer;
    written_amount(myAmount, buffer);


    cout << buffer << endl;


    getchar();


return 0;
}
0 0