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

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

Problem

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

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

class Solution {    private String[] belowTen = new String[] {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};    private String[] tenToTwenty = new String[] {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};    private String[] tens = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};        public String numberToWords(int num) {        if (num == 0) return "Zero";        return helper(num);    }        private String helper(int num) {        String result;        if (num < 10) result = belowTen[num];        else if (num < 20) result = tenToTwenty[num-10];        else if (num < 100) result = tens[num/10] + " " + belowTen[num%10];        else if (num < 1000) result = belowTen[num/100] + " Hundred " + helper(num%100);        else if (num < 10000) result = belowTen[num/1000] + " Thousand " + helper(num%1000);        else if (num < 1000000) result = helper(num/1000) + " Thousand " + helper(num%1000);        else if (num < 1000000000) result = helper(num/1000000) + " Million " + helper(num%1000000);        else result = helper(num/1000000000) + " Billion " + helper(num%1000000000);        return result.trim();    }}

转载地址:http://dmael.baihongyu.com/

你可能感兴趣的文章
PayPal API风格指南和设计模式
查看>>
02-Docker新手入门网络篇
查看>>
大神 Linus Torvalds 语录
查看>>
[LintCode/LeetCode] Find Median From / Data Stream Median
查看>>
Android开发套路收集整理与讨论
查看>>
代码规范的重要性,我已经放弃治疗
查看>>
笨办法学C 练习30:自动化测试
查看>>
mui初级入门教程(五)— 聊聊即时通讯(IM),基于环信 web im SDK
查看>>
[vs2008]Visual Studio 2008 SP1添加或删除功能提示查找SQLSysClrTypes.msi文件
查看>>
JS 设计模式二(封装)
查看>>
JavaScript “跑马灯”抽奖活动代码解析与优化(一)
查看>>
为什么我们选择 segmentfault 写作?
查看>>
多模型融合推荐算法在达观数据的运用
查看>>
JDK 11 马上就要来了!JDK 12 还会远吗?
查看>>
Kali Linux 2019.1 发布,Metasploit 更新到 5.0 版本
查看>>
【mysql的设计与优化专题(1)】ER图,数据建模与数据字典
查看>>
Jibo’s Name: How did we pick it?
查看>>
device's media capture mechanism,利用input:file调用设备的照相机/相册、摄像机、录音机...
查看>>
BroadLink:三款新品力求无障碍人机交互,三大平台分三期对外开放 ...
查看>>
掌门1对1获3.5亿美元E-1轮融资,华人文化产业基金、中金甲子基金等投资 ...
查看>>