这道题并不难,但是特别麻烦
我写的代码
class Solution { public: //转换个位数的英文 string baseNumber(int num){ if(num == 1) return "One"; else if(num == 2) return "Two"; else if(num == 3) return "Three"; else if(num == 4) return "Four"; else if(num == 5) return "Five"; else if(num == 6) return "Six"; else if(num == 7) return "Seven"; else if(num == 8) return "Eight"; else if(num == 9) return "Nine"; else return ""; //个位是0,返回空串 } //转换两位数的英文 string tenNumber(int num){ if(num == 0) return ""; //两位数都是0,返回空串 if(num >= 10 && num <= 19){ if(num == 10) return "Ten"; else if(num == 11) return "Eleven"; else if(num == 12) return "Twelve"; else if(num == 13) return "Thirteen"; else if(num == 14) return "Fourteen"; else if(num == 15) return "Fifteen"; else if(num == 16) return "Sixteen"; else if(num == 17) return "Seventeen"; else if(num == 18) return "Eighteen"; else if(num == 19) return "Nineteen"; } else if(num <= 9) return baseNumber(num); //接下来的是20-99的转换 int ten = num/10; int base = num%10; string res = ""; //twenty thirty fourty fifty sixty seventy eighty ninety if(ten == 2) res+="Twenty"; else if(ten == 3) res+="Thirty"; else if(ten == 4) res+="Forty"; else if(ten == 5) res+="Fifty"; else if(ten == 6) res+="Sixty"; else if(ten == 7) res+="Seventy"; else if(ten == 8) res+="Eighty"; else if(ten == 9) res+="Ninety"; if(base == 0) return res; return res + " " + baseNumber(base); } //转换三位数的英文 string hundredNumber(int num){ if(num == 0) return ""; //三位数都是0,返回空串 if(num < 100) return tenNumber(num); if(num % 100 == 0) return baseNumber(num/100) + " " + "Hundred"; return baseNumber(num / 100) + " " + "Hundred" + " " + tenNumber(num % 100); } string numberToWords(int num) { if(num == 0) return "Zero"; string res=""; //hundred 100 thousand 1000 million 1000000 billion 1000000000 int billion = num / 1000000000; if(billion != 0) res = res + baseNumber(billion) + " " + "Billion" + " "; num = num % 1000000000; int million = num / 1000000; if(million != 0) res = res + hundredNumber(million) + " " + "Million" + " "; num = num % 1000000; int thousand = num / 1000; if(thousand != 0) res = res + hundredNumber(thousand) + " " + "Thousand" + " "; num = num % 1000; res = res + hundredNumber(num); if(res[res.size()-1] == ' ') res.pop_back();//如果最后有多余的空格就去掉 return res; } };
标签:return,num,else,273,整数,英文,转换,leetcode From: https://www.cnblogs.com/uacs2024/p/18546048