博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Integer to English Words
阅读量:7106 次
发布时间:2019-06-28

本文共 1794 字,大约阅读时间需要 5 分钟。

This problem is not difficult. But it is not easy to have a bug-free code. As you write your codes according to the hints, the most important thing is to handle all the edge cases without making the code ugly :-) Well, the key to simplify the code is to us hard coding. provides a nice solution, whose Java code is rewritten below in C++. Since C++ has no convenient functions like trim and I do not want to create one on my own, I handle the " " and ' ' carefully using some tricks from  (for example, I include the space in the words of the numbers).

1 class Solution { 2 public:  3     string numberToWords(int num) { 4         vector
bigs = { "", " Thousand", " Million", " Billion" }; 5 int i = 0; 6 string ans; 7 while (num) { 8 if (num % 1000) ans = numberWords(num % 1000) + bigs[i] + ans; 9 i++, num /= 1000;10 }11 return ans.length() ? ans.substr(1) : "Zero";12 }13 private:14 string numberWords(int num) {15 char* one[] = { "", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine" };16 char* ones[] = { " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen" };17 char* tens[] = { "", "", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety" };18 string ans;19 if (num > 99) ans += string(one[num / 100]) + " Hundred";20 num %= 100;21 if (num > 9 && num < 20) ans += ones[num % 10];22 else {23 if (num > 19) ans += tens[num / 10];24 num %= 10;25 if (num) ans += one[num];26 }27 return ans;28 }29 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4774090.html

你可能感兴趣的文章
【学习笔记】CSS深入理解之margin
查看>>
MySQL集群搭建(4)-MMM+LVS+Keepalived
查看>>
Hive database does not exist 排查
查看>>
为什么要用Log4j来替代System.out.println
查看>>
如何使用IconFont?——矢量图标
查看>>
详谈vue组件间事件派发与接收
查看>>
ApacheCN 学习资源汇总 2018.12
查看>>
用node探究下http缓存
查看>>
js实现复制粘贴功能
查看>>
前端开发中提到的“脚手架”到底指什么,CLI?gulp 和 gulp-cli有什么区别
查看>>
Ghost配置4——添加网站统计
查看>>
在keystone.js后台编辑器中上传图片
查看>>
请求限流
查看>>
微信小程序网络通信(一)
查看>>
Data Lake Analytics-数据分析时代迎来新变革
查看>>
Vue.js 组件库事件系统设计
查看>>
移动端模拟滚动
查看>>
webpack4.17.1起步
查看>>
linux user xxx is not allowed to execute '/bin/su'
查看>>
Meteor部署问题汇总
查看>>