273. Integer to English Words
来源:互联网 发布:淘宝每天领取1元红包 编辑:程序博客网 时间:2024/05/17 08:30
Task:
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"
Some Questions:
How to spell 1 to 19?
How to spell 20,30,40,...,90?
Solution:
According to the grammar, it reads integer three digits by three digits. So we can convert the Integer into English three digits by three digits.
Thus we need to implement a helper to convert a number within 1000. At last, For every group of three digits, add the suffix of weight to it.
Attention to corner cases!
Code:
class Solution { const string Mil="Million"; const string Tho="Thousand"; const string Bil="Billion"; const string Hun="Hundred"; string tab[20]={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; string tens[10]={"Zero","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; string calc(int n,int w) { if(n==0)return ""; string ret=""; if(n>=100) { if(ret!="")ret+=" "; ret+=tab[n/100]+" "+Hun; } n%=100; if(n>0) { if(n<20) { if(ret!="")ret+=" "; ret+=tab[n]; } else { if(ret!="")ret+=" "; if(n%10!=0) { ret+=tens[n/10]+" "+tab[n%10]; } else ret+=tens[n/10]; } } if(w==1) { ret+=" "+Tho; } else if(w==2) { ret+=" "+Mil; } else if(w==3) { ret+=" "+Bil; } return ret; }public: string numberToWords(long long num) { int bit[4]; string ret=""; int len=0; if(num==0)return "Zero"; while(num) { bit[len++]=num%1000; num/=1000; } int i; for(i=len-1;i>=0;i--) { string tmp=calc(bit[i],i); if(tmp!="") { if(ret!="")ret+=" "; ret+=tmp; } } return ret; }};
0 0
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- 273. Integer to English Words
- Integer to English Words
- Integer to English Words
- Integer to English Words
- Integer to English Words
- Integer to English Words
- Integer to English Words
- 音乐播放器
- qsort函数用法
- C++中operator的主要用法
- C#编程基础 实验(6) (1-3)
- logistic回归详解一:为什么要使用logistic函数
- 273. Integer to English Words
- 299. Bulls and Cows
- Ruby on Rails 路由解析
- 实现从ActiveX调用网页中的javascript函数.
- solr配置_schema.xml和solrconf.xml
- 计算机网络ip地址分类及含义
- Python日常
- 合并两个有序链表,合并后依然有序(C语言)
- linux下的线程