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

后端 未结 8 556
名媛妹妹
名媛妹妹 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 11:55

    Instead of switch statements, consider using tables of strings indexed by a small value.

    const char * const ones[20] = {"zero", "one", "two", ..., "nineteen"};
    const char * const tens[10] = {"", "ten", "twenty", ..., "ninety"};
    

    Now break the problem into small pieces. Write a function that can output a single-digit number. Then write a function that can handle a two-digit number (which will probably use the previous function). Continue building up the functions as necessary.

    Create a list of test cases with expected output, and write code to call your functions and check the output, so that, as you fix problems for the more complicated cases, you can be sure that the simpler cases continue to work.

提交回复
热议问题