Integer to English Words

来源:互联网 发布:中国电信网络重构原则 编辑:程序博客网 时间:2024/05/18 03:39

一、问题描述

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,

123 -> "One Hundred Twenty Three"12345 -> "Twelve Thousand Three Hundred Forty Five"1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Hint:

  1. Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
  2. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
  3. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)

二、思路

和另一个题目‘’整形数字转化为罗马数字‘’有些类似:Integer to Roman

三、代码

class Solution {public:    string numberToWords(int num) {        string s = "";        string englishWord[] = {"Billion","Million","Thousand","Hundred","Ninety","Eighty","Seventy","Sixty","Fifty","Forty","Thirty","Twenty","Nineteen","Eighteen","Seventeen","Sixteen","Fifteen","Fourteen","Thirteen","Twelve","Eleven","Ten","Nine","Eight","Seven","Six","Five","Four","Three","Two","One"};        int nums[] = {1000000000,1000000,1000,100,90,80,70,60,50,40,30,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};        if(num == 0)             return "Zero";        int i = 0;        for(; num < nums[i]; ++i);        int upper = num / nums[i];        int lower = num % nums[i];        return (i < 4 ? numberToWords(upper) + " " : "") + englishWord[i] + (lower? " " + numberToWords(lower) : "");    }};


0 0
原创粉丝点击