Java实现 LeetCode 273 整数转换英文表示
2024-10-09 02:30:56
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();
}
}
最新文章
- 基于AngularJS的个推前端云组件探秘
- 二、CoreAnimation之寄宿图详解
- Java基础知识点3:集合类
- psoame
- 实现类似QQ对话聊天功能脚本
- 【故障处理】告警日志报“ORA-01565 Unable To open Spfile”
- android oom 全解析
- NSIS打包(一)常用概念简介
- 空间插值文献阅读(Geostatistical approaches for incorporating elevation into the spatial interpolation of rainfall)
- C语言的几种取整方法
- hihoCoder挑战赛11 A 随机斐波那契
- Sencha Cmd的简介
- Java基础——关于访问权限的一道例题
- JDBCTemplate
- 从架构演进的角度聊聊Spring Cloud都做了些什么?
- java 中的instanceof
- Python爬虫学习--用Python结合Selenium实现 明日之子节目直播时为自己喜欢的选手自动点赞拉票!!!
- liunx存储管理之基础知识
- 《剑指offer》-青蛙跳台阶II
- Codeforces 579A. Raising Bacteria
热门文章
- python语法学习第十一天--模块
- Python语法学习第三天--元组
- [hdu5439 Aggregated Counting]公式化简,预处理
- python 一个模块找不到的错误:ModuleNotFoundError
- 切片原型[start:stop:step]
- Mockito如何mock一条链式调用
- rabbitMQ基于spring-rabbitnq
- shell 并行运行。
- wepy 小程序开发(Mixin混合)
- Hbase javaAPI报错:Callexception,tries=10,retries=35,started=38465msago