LeetCode 273. Integer to English Words

Facebook full-time 的面试题。

遇到这种数字的题,第一感觉就是递归。而且一定要问清楚数字给定的范围,会不会是负数,有没有范围等等。题目给定了范围 0~2^31-1,因此最高到 billion。

根据大小来拆分然后递归,注意一些corner cases,1~19,20,30,……

总体不难,别慌慢慢想,各种情况想清楚就行。

class Solution {
public:
    string numberToWords(int num) {
        if (num==0) return "Zero";
        return convert(num).substr(1);
    }
    
    string convert(int num){
        if (num>=1000000000) return convert(num/1000000000) + " Billion" + convert(num%1000000000);
        else if (num>=1000000) return convert(num/1000000) + " Million" + convert(num%1000000);
        else if (num>=1000) return convert(num/1000) + " Thousand" + convert(num%1000);
        else if (num>=100) return convert(num/100) + " Hundred" + convert(num%100);
        else if (num>=20) return " " + ten[num/10] + convert(num%10);
        else if (num>=1)return " " + map[num];
        return "";
    }
    
private:
    string map[20] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    string ten[11] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
};

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/9540382.html