[hard]273. Integer to English Words
来源:互联网 发布:重庆淘宝店铺运营公司 编辑:程序博客网 时间:2024/06/04 19:58
<span style="font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">273. Integer to English Words</span>
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"
Solution:
It's a super easy problem. Just make sure you have every detail checked.
(Forgot to install a Chinese language input, sorry
Here is my code.
class Solution {public: string num[9] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; string teens[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; string tens[8] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; string units[4] = {"", "Thousand", "Million", "Billion"}; string under_1000(int x) { string ans; int hun = x / 100; int ten = (x % 100) / 10; int sig = x % 10; bool first = true; if (hun) { ans += num[hun - 1] + " Hundred"; first = false; } if (ten) { if (ten >= 2) { if (!first) ans += ' '; ans += tens[ten - 2]; if (sig) ans += ' ' + num[sig - 1]; first = false; } else { if (!first) ans += ' '; ans += teens[sig]; } } else { if (sig) { if (!first) ans += ' '; ans += num[sig - 1]; } } return ans; } string numberToWords(int num) { string ans; int count = 0; if (!num) return "Zero"; while (num) { if (num % 1000 != 0) { string str = under_1000(num % 1000); if (str != "") if (ans != "") ans = str + ' ' + units[count] + ' ' + ans; else if (units[count] != "") ans = str + ' ' + units[count]; else ans = str; } num /= 1000; ++ count; } return ans; }};
0 0
- [hard]273. Integer to English Words
- Hard-题目49:273. Integer to English Words
- Hard 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
- 273. Integer to English Words
- Integer to English Words
- Integer to English Words
- Integer to English Words
- 机器学习基石(林轩田)——笔记1
- 大话-从市场需求->芯片设计->SDK开发->Turnkey方案->定制化产品 --- SDK开发(三) 即将开启大话专题 ISP篇,希望喜欢大话技术的读者加群147565042,我们一起“吹”集结号
- 灰常简易的顺序队列
- 小波的秘密10_图像处理应用:图像增强
- MongoDB 那些坑
- [hard]273. Integer to English Words
- django
- NYOJ 104 - 最大和
- 实现可变参数函数:Max,求最大值。
- Android 6.0关机流程图
- 扩展性、易用性 浅谈游戏状态机的设计与实现
- JZOJ 4863. 【GDOI2017模拟11.5】Market
- 剑指offer:面试题9,斐波那契数列
- HDU-2874-Connections between cities