题目:
273. Integer to English Words
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"
答案:
按着自己用英文阅读整数的顺序来就行:
1、这道题目不是难在思路上,而是难在考虑的情况比较多,比较多细节,一不小心就有小bug,需要思路清晰,逻辑清晰
2、英文中用来表示整数的单词并不多,分类:
1-9(个位数),11-19(特殊的十位数),10-90(十位数),100(hundred),1000(thousand),1000000(million),1000000000(billion)
3、10这个十位数比较特别,只有在后两位完全为10时,才用ten
4、注意空格,后面没有数字了,就不能加空格了
5、每千位数跟后面的千位数(如果不为空,即0000000……)要有空格
6、注意不要乱加前缀空格和后缀空格
将上面的细节注意了就AC啦
代码:
1 #include <vector> 2 #include <string> 3 4 using std::vector; 5 using std::string; 6 7 string n2s[] = {"One","Two","Three","Four","Five","Six","Seven","Eight","Nine"}; 8 string g2s[] = {"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; 9 string t2s[] = {"Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; 10 11 class Solution { 12 private: 13 vector<string> ans; 14 15 public: 16 string numberToWords(int num) { 17 if(num == 0) 18 { 19 return "Zero"; 20 } 21 22 unsigned int rem; 23 unsigned int one; 24 unsigned int two; 25 unsigned int three; 26 27 string perAns; 28 ans.clear(); 29 30 do 31 { 32 //获取余数 33 rem = num % 1000; 34 num = num /1000; 35 36 //存储每次计算的结果 37 perAns.clear(); 38 perAns = ""; 39 40 //一千以内的数,取每一位 41 one = rem % 10; 42 two = (rem / 10) % 10; 43 three = (rem / 100) % 10; 44 45 if(three != 0) 46 { 47 perAns += n2s[three - 1]; 48 perAns += " Hundred"; 49 } 50 51 //如果后两位都为0,那么后面就没有数了,也就不需要加空格 52 if(perAns != "" && (one != 0 || two != 0)) 53 { 54 perAns += " "; 55 } 56 57 if(two == 1) 58 { 59 //考虑最后一位是否为0的情况,因最后两位为10时,需要用“ten” 60 //否则就是十位数 61 if(one == 0) 62 { 63 perAns += t2s[0]; 64 }else 65 { 66 perAns += g2s[one - 1]; 67 } 68 //考虑two不为0,不为1,则按一般规则去计算 69 }else if(two != 0) 70 { 71 perAns += t2s[two - 1]; 72 73 if(one != 0) 74 { 75 perAns += " ";//如果最后一位不为0,需要在其前面加空格 76 perAns += n2s[one - 1]; 77 } 78 //考虑two为0的情况 79 }else 80 { 81 if(one != 0) 82 { 83 perAns += n2s[one - 1]; 84 } 85 } 86 87 //将结果存储到ans中,ans中的答案是以逆序形式存储了每个千位数 88 ans.push_back(perAns); 89 }while(num != 0); 90 91 string result = ""; 92 unsigned int len = ans.size(); 93 //len最大长度为4,考虑每种位数就行,这里用的时候就会发现,合理使用goto,程序逻辑会很清晰 94 switch(len) 95 { 96 case 4:goto three;break; 97 case 3:goto two;break; 98 case 2:goto one;break; 99 case 1:goto zero;break; 100 } 101 102 three: 103 if(ans[3] != "") 104 { 105 result += ans[3]; 106 result += " Billion"; 107 108 if(ans[2] != "" || ans[1] != "" || ans[0] != "") 109 { 110 result += " "; 111 } 112 } 113 114 two: 115 if(ans[2] != "") 116 { 117 result += ans[2]; 118 result += " Million"; 119 120 if(ans[1] != "" || ans[0] != "") 121 { 122 result += " "; 123 } 124 } 125 126 one: 127 if(ans[1] != "") 128 { 129 result += ans[1]; 130 result += " Thousand"; 131 132 if(ans[0] != "") 133 { 134 result += " "; 135 } 136 } 137 138 zero: 139 if(ans[0] != "") 140 { 141 result += ans[0]; 142 } 143 144 return result; 145 } 146 };
说明: 合理使用goto会取到很好的效果哦