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

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

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:

  1. Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
  2. 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.
  3. 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)

一定要考虑各种边界情况。正如提示里所说的。

1 class Solution { 2 public: 3     string getWord(int num, string *digit, string *digit1) { 4         if (num == 0) return "Zero"; 5         string res; 6         int h = num / 100; 7         num %= 100; 8         if (h > 0) res += digit[h] + " Hundred"; 9         if (num == 0) return res;10         else if (h > 0) res += " ";11         if (num < 20) {12             res += digit[num];13         } else {14             h = num / 10;15             num %= 10;16             res += digit1[h];17             if (num != 0) res += " " + digit[num];18         }19         return res;20     }21     string numberToWords(int num) {22         if (num == 0) return "Zero";23         string digit[20] = {
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",24 "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"25 };26 string digit1[10] = {
"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};27 string digit2[10] = {
"", "Thousand", "Million", "Billion"};28 vector
words;29 string str;30 int num2, cnt = 0;31 while (num != 0) {32 num2 = num % 1000;33 str = getWord(num2, digit, digit1);34 if (str != "Zero") {35 if (cnt > 0) words.push_back(str + " " + digit2[cnt]);36 else words.push_back(str);37 }38 num /= 1000;39 ++cnt;40 }41 string res;42 for (int i = (int)words.size() - 1; i > 0; --i) {43 res += words[i] + " ";44 }45 res += words.front();46 return res;47 }48 };

 

转载于:https://www.cnblogs.com/easonliu/p/4772781.html

你可能感兴趣的文章
Linux环境下MySql安装和常见问题的解决
查看>>
lrzsz——一款好用的文件互传工具
查看>>
ZPL语言完成条形码的打印
查看>>
这20件事千万不要对自己做!
查看>>
Linux环境下Redis安装和常见问题的解决
查看>>
Android开发中常见问题分析及解决
查看>>
玩转小程序之文件读写
查看>>
Android开发中UI相关的问题总结
查看>>
MySql Host is blocked because of many connection errors 问题的解决方法
查看>>
FastDFS高可用集群架构配置搭建及使用
查看>>
.tar.gz文件和.tar.xz文件的解压和压缩
查看>>
HashPump用法
查看>>
RabbitMQ的安装
查看>>
Halcon匹配方法
查看>>
Linux安装libcholmod-dev找不到的解决方法
查看>>
cuda基础
查看>>
吉林大学考研复试题目(牛客网)
查看>>
最长公共子序列与最长公共字串
查看>>
动态规划之工作方案
查看>>
React的三大属性
查看>>