Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

后端 未结 8 549
名媛妹妹
名媛妹妹 2021-02-01 11:37

Write C/C++/Java code to convert given number into words.

eg:- Input: 1234

Output: One thousand two hundred thirty-four.

Input: 10

Output: Ten

8条回答
  •  伪装坚强ぢ
    2021-02-01 12:13

    if you are interested in a ready solution then you may look at HumanizerCpp library (https://github.com/trodevel/HumanizerCpp) - it is a port of C# Humanizer library and it does exactly what you want.

    It can even convert to ordinals and currently supports 3 languages: English, German and Russian.

    Example:

    const INumberToWordsConverter * e = Configurator::GetNumberToWordsConverter( "en" );
    
    std::cout << e->Convert( 123 ) << std::endl;
    std::cout << e->Convert( 1234 ) << std::endl;
    std::cout << e->Convert( 12345 ) << std::endl;
    std::cout << e->Convert( 123456 ) << std::endl;
    
    std::cout << std::endl;
    std::cout << e->ConvertToOrdinal( 1001 ) << std::endl;
    std::cout << e->ConvertToOrdinal( 1021 ) << std::endl;
    
    
    const INumberToWordsConverter * g = Configurator::GetNumberToWordsConverter( "de" );
    
    std::cout << std::endl;
    std::cout << g->Convert( 123456 ) << std::endl;
    
    const INumberToWordsConverter * r = Configurator::GetNumberToWordsConverter( "ru" );
    
    std::cout << r->ConvertToOrdinal( 1112 ) << std::endl;
    

    Output:

    one hundred and twenty-three
    one thousand two hundred and thirty-four
    twelve thousand three hundred and forty-five
    one hundred and twenty-three thousand four hundred and fifty-six
    
    thousand and first
    thousand and twenty-first
    
    einhundertdreiundzwanzigtausendvierhundertsechsundfünfzig
    одна тысяча сто двенадцатый
    

    In any case you may take a look at the source code and reuse in your project or try to understand the logic. It is written in pure C++ without external libraries.

    Regards, Serge

提交回复
热议问题