Integer to English Words
来源:互联网 发布:中国电信网络重构原则 编辑:程序博客网 时间:2024/05/18 03:39
一、问题描述
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)
二、思路
和另一个题目‘’整形数字转化为罗马数字‘’有些类似:Integer to Roman
三、代码
class Solution {public: string numberToWords(int num) { string s = ""; string englishWord[] = {"Billion","Million","Thousand","Hundred","Ninety","Eighty","Seventy","Sixty","Fifty","Forty","Thirty","Twenty","Nineteen","Eighteen","Seventeen","Sixteen","Fifteen","Fourteen","Thirteen","Twelve","Eleven","Ten","Nine","Eight","Seven","Six","Five","Four","Three","Two","One"}; int nums[] = {1000000000,1000000,1000,100,90,80,70,60,50,40,30,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1}; if(num == 0) return "Zero"; int i = 0; for(; num < nums[i]; ++i); int upper = num / nums[i]; int lower = num % nums[i]; return (i < 4 ? numberToWords(upper) + " " : "") + englishWord[i] + (lower? " " + numberToWords(lower) : ""); }};
0 0
- 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 - Integer to English Words
- [leetcode] Integer to English Words
- Integer to English Words -- leetcode
- LeetCode273:Integer to English Words
- JMM和synchronize的一些记录:
- JVM内存区域介绍
- 软件测试的一些理解
- Android基础(三)
- Leetcode 234. Palindrome Linked List (Easy) (cpp)
- Integer to English Words
- 关于解决git冲突
- jQuery学习<一> — — 安装
- KMP模板
- 计算类的大小--字节对齐
- 可访问性不一致: 属性类型“ ”比属性“ ”的可访问性低
- GeekBand第十周笔记
- HDOJ 1713 相遇周期
- jquery实现的Ajax局部刷新