LintCode 1305: Integer to English Words

1305. Integer to English Words

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

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"

Input test data (one parameter per line)How to understand a testcase?

解法1:

参考的网上思路。我觉得这个解法很清晰。

注意:
1) 不要用1e+9代替1000000000,或用1e+6代替1000000。因为C++把1e+9这样的科学计数法当成double型,所以num % 1e+9会有问题。
2) 最后的result前面会多个空格,要消掉。
3)         } else if (num >= 20) {
            return " " + tens[num / 10] + helper(num % 10);

不可写成return " " + tens[num / 10] + " " + digits[num % 10];
否则680901192会生成
"Six Hundred Eighty Zero Million Nine Hundred One Thousand One Hundred Ninety Two",多了一个Zero。

class Solution {
public:
    /**
     * @param num: a non-negative integer
     * @return: english words representation
     */
    string numberToWords(int num) {
        if (num == 0) return "Zero";
        string result = helper(num);
        
        return result.substr(1); //skip the beginning " "
    }
    
private:
    vector<string> digits = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    vector<string> tens = {"Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    
    string helper(int num) {
        if (num >= 1000000000) { //Billion 
            return helper(num / 1000000000) + " Billion" + helper(num % 1000000000);
        } else if (num >= 1000000) { //Million
            return helper(num / 1000000) + " Million" + helper(num % 1000000);
        } else if (num >= 1000) { //Thousand
            return helper(num / 1000) + " Thousand" + helper(num % 1000);
        } else if (num >= 100) { //Hundred
            return helper(num / 100) + " Hundred" + helper(num % 100);
        } else if (num >= 20) {
            return " " + tens[num / 10] + helper(num % 10);
        } else if (num >= 1) {
            return " "+ digits[num];
        } else {
            return "";
        }
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值