Integer to English Words 整数转换为英语表示
来源:互联网 发布:和英国女人 知乎 编辑:程序博客网 时间:2024/05/22 12:44
Integer to English Words
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"
Hint:
- Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
- Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
- There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
class Solution {public://从右向左处理 string numberToWords(int num) { string ans; int k=0; while(num) { if(num%1000) ans = solve(num%1000)+bigs[k]+ans; k++; num/=1000; } return ans.length()? ans.substr(1):"Zero";//去除第一位前的空格 } //最多三位数 string solve(int num) { string res; if(num>=100) res = res + map1[num/100]+" Hundred"; num%=100; if(num>=10 && num<20) res += map1[num]; else { if(num>19) res+= map2[num/10]; num%=10; res+= map1[num]; } return res; } private: vector<string> map1={"", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine", " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen"}; vector<string> map2= {"", "", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety"}; vector<string> bigs={"", " Thousand", " Million", " Billion" }; };
0 0
- Integer to English Words 整数转换为英语表示
- LeetCode 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
- 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
- Integer to English Words
- Integer to English Words
- LeetCode OJ 之 Integer to English Words(整数转化为英文单词)
- 剖析Android中进程与线程调度之nice
- SpannableString、SpannableStringBuilder与String的关系
- 任何时间,都可以开始
- 队列的两种实现:数组和链表
- IOS 本地保存Crash日志信息
- Integer to English Words 整数转换为英语表示
- Kafka设计解析(二):Kafka High Availability (上)
- android 群组头像的显示(仿QQ群组)
- hdu 2014 青年歌手大奖赛_评委会打分
- 比较两个字符串A和B,确定A中是否包含B中所有的字符。
- 【Unity3D游戏开发】之全局管理类的几种方式 (十六)
- 纯CSS实现家谱树(组织架构树同理)
- linux下weblogic12c集群的安装部署
- JAVA 计算根据经纬度计算距离