LeetCode-273. Integer to English Words

来源:互联网 发布:mac 安装sass 编辑:程序博客网 时间:2024/06/04 01:38

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"

class Solution {public:    string numberToWords(int num) {        if(num == 0) return "Zero";        return stringToWord(num).substr(1); //.substr(1) 舍弃掉开头的空格    }private:    static const string below_20[];    static const string below_100[];    string stringToWord(int num){ //不要忘了空格空格空格,以及这里不好用循环        if(num >= 1000000000)   return stringToWord(num / 1000000000) + " Billion" + stringToWord(num % 1000000000);        else if(num >= 1000000) return stringToWord(num / 1000000) + " Million" + stringToWord(num % 1000000);        else if(num >= 1000)    return stringToWord(num / 1000) + " Thousand" + stringToWord(num % 1000);        else if(num >= 100)     return stringToWord(num / 100) + " Hundred" + stringToWord(num % 100);        else if(num >= 20)      return string(" ") + below_100[num / 10 - 2] + stringToWord(num % 10);        else if(num >= 1)       return string(" ") + below_20[num - 1];        else return "";    }};const string Solution::below_20[] = {"One", "Two", "Three", "Four","Five","Six","Seven","Eight","Nine","Ten", "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};const string Solution::below_100[] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};


0 0
原创粉丝点击