273. 整数转换英文表示

将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。

示例 1:

输入: 123

输出: “One Hundred Twenty Three”

示例 2:

输入: 12345

输出: “Twelve Thousand Three Hundred Forty Five”

示例 3:

输入: 1234567

输出: “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”

示例 4:

输入: 1234567891

输出: “One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One”

class Solution {
final static String[] zeroToNineteen = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
"Eighteen", "Nineteen"};
final static String[] twentyToNinety = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
final int BILLION = 1000000000;
final int MILLION = 1000000;
final int THOUSAND = 1000;
final int HUNDRED = 100;
public String numberToWords(int num) {
if (num == 0) return "Zero";
StringBuilder builder = new StringBuilder();
if (num >= BILLION) {
if (builder.length() != 0) builder.append(" ");
builder.append(numberToWords(num / BILLION)).append(" Billion");
num %= BILLION;
}
if (num >= MILLION) {
if (builder.length() != 0) builder.append(" ");
builder.append(numberToWords(num / MILLION)).append(" Million");
num %= MILLION;
}
if (num >= THOUSAND) {
if (builder.length() != 0) builder.append(" ");
builder.append(numberToWords(num / THOUSAND)).append(" Thousand");
num %= THOUSAND;
}
if (num >= HUNDRED) {
if (builder.length() != 0) builder.append(" ");
builder.append(numberToWords(num / HUNDRED)).append(" Hundred");
num %= HUNDRED;
}
if (num < 20) {
if (num != 0) {
if (builder.length() != 0) builder.append(" ");
builder.append(zeroToNineteen[num]);
}
}
else {
if (builder.length() != 0) builder.append(" ");
builder.append(twentyToNinety[num / 10 - 2]);
if (num % 10 != 0) {
if (builder.length() != 0) builder.append(" ");
builder.append(zeroToNineteen[num % 10]);
}
}
return builder.toString();
}
}

最新文章

  1. 基于AngularJS的个推前端云组件探秘
  2. 二、CoreAnimation之寄宿图详解
  3. Java基础知识点3:集合类
  4. psoame
  5. 实现类似QQ对话聊天功能脚本
  6. 【故障处理】告警日志报“ORA-01565 Unable To open Spfile”
  7. android oom 全解析
  8. NSIS打包(一)常用概念简介
  9. 空间插值文献阅读(Geostatistical approaches for incorporating elevation into the spatial interpolation of rainfall)
  10. C语言的几种取整方法
  11. hihoCoder挑战赛11 A 随机斐波那契
  12. Sencha Cmd的简介
  13. Java基础——关于访问权限的一道例题
  14. JDBCTemplate
  15. 从架构演进的角度聊聊Spring Cloud都做了些什么?
  16. java 中的instanceof
  17. Python爬虫学习--用Python结合Selenium实现 明日之子节目直播时为自己喜欢的选手自动点赞拉票!!!
  18. liunx存储管理之基础知识
  19. 《剑指offer》-青蛙跳台阶II
  20. Codeforces 579A. Raising Bacteria

热门文章

  1. python语法学习第十一天--模块
  2. Python语法学习第三天--元组
  3. [hdu5439 Aggregated Counting]公式化简,预处理
  4. python 一个模块找不到的错误:ModuleNotFoundError
  5. 切片原型[start:stop:step]
  6. Mockito如何mock一条链式调用
  7. rabbitMQ基于spring-rabbitnq
  8. shell 并行运行。
  9. wepy 小程序开发(Mixin混合)
  10. Hbase javaAPI报错:Callexception,tries=10,retries=35,started=38465msago