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

Example 1:

Input: 123
Output: "One Hundred Twenty Three"

Example 2:

Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety

新版题目没有提示了。

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)

将一个整数转换成英文单词。提示:要3个一组进行处理,限定了数字范围为0到2^31 - 1之间,最高只能到billion位,只需处理四组。

每三位一组进行处理,每加一组就加上units,整数除以1000,对1000取余。处理范围分为99以上,20~99,10~20,0~10。先写出不同的数字范围英文单词列表,然后根据范围添加到结果中。

F家:可能是负数

Java:

class Solution {
public String numberToWords(int num) {
String[] units = {""," Thousand"," Million"," Billion"};
int i = 0;
String res="";
while(num > 0) {
int temp = num % 1000;
if(temp > 0) res = convert(temp) + units[i] + (res.length()==0 ?"": " "+res);
num /= 1000;
i++;
}
return res.isEmpty()? "Zero" : res;
}
public String convert(int num){
String res = "";
String[] ten = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
String[] hundred = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
String[] twenty = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
if(num>0) {
int temp = num / 100;
if(temp > 0) {
res += ten[temp] + " Hundred";
}
temp = num%100;
if(temp >= 10 && temp < 20){
if(!res.isEmpty()) res +=" ";
res = res + twenty[temp%10];
return res;
}else if(temp >= 20){
temp = temp / 10;
if(!res.isEmpty()) res +=" ";
res = res + hundred[temp-1];
}
temp = num % 10;
if(temp > 0) {
if(!res.isEmpty()) res +=" ";
res = res + ten[temp];
}
}
return res;
}
}
}

Python:

class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "Zero" lookup = {0: "Zero", 1:"One", 2: "Two", 3: "Three", 4: "Four", \
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", \
10: "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", \
15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen", \
20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", \
70: "Seventy", 80: "Eighty", 90: "Ninety"}
unit = ["", "Thousand", "Million", "Billion"] res, i = [], 0
while num:
cur = num % 1000
if num % 1000:
res.append(self.threeDigits(cur, lookup, unit[i]))
num //= 1000
i += 1
return " ".join(res[::-1]) def threeDigits(self, num, lookup, unit):
res = []
if num / 100:
res = [lookup[num / 100] + " " + "Hundred"]
if num % 100:
res.append(self.twoDigits(num % 100, lookup))
if unit != "":
res.append(unit)
return " ".join(res) def twoDigits(self, num, lookup):
if num in lookup:
return lookup[num]
return lookup[(num / 10) * 10] + " " + lookup[num % 10]  

Python:

class Solution(object):
def numberToWords(self, num):
lv1 = "Zero One Two Three Four Five Six Seven Eight Nine Ten \
Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen".split()
lv2 = "Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety".split()
lv3 = "Hundred"
lv4 = "Thousand Million Billion".split()
words, digits = [], 0
while num:
token, num = num % 1000, num / 1000
word = ''
if token > 99:
word += lv1[token / 100] + ' ' + lv3 + ' '
token %= 100
if token > 19:
word += lv2[token / 10 - 2] + ' '
token %= 10
if token > 0:
word += lv1[token] + ' '
word = word.strip()
if word:
word += ' ' + lv4[digits - 1] if digits else ''
words += word,
digits += 1
return ' '.join(words[::-1]) or 'Zero'

C++:

class Solution {
public:
string numberToWords(int num) {
string res = convertHundred(num % 1000);
vector<string> v = {"Thousand", "Million", "Billion"};
for (int i = 0; i < 3; ++i) {
num /= 1000;
res = num % 1000 ? convertHundred(num % 1000) + " " + v[i] + " " + res : res;
}
while (res.back() == ' ') res.pop_back();
return res.empty() ? "Zero" : res;
}
string convertHundred(int num) {
vector<string> v1 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
vector<string> v2 = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string res;
int a = num / 100, b = num % 100, c = num % 10;
res = b < 20 ? v1[b] : v2[b / 10] + (c ? " " + v1[c] : "");
if (a > 0) res = v1[a] + " Hundred" + (b ? " " + res : "");
return res;
}
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 273. Integer to English Words 整数转为英文单词的更多相关文章

  1. [leetcode]273. Integer to English Words 整数转英文单词

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

  2. [LeetCode] Integer to English Words 整数转为英文单词

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

  3. leetcode@ [273] Integer to English Words (String & Math)

    https://leetcode.com/problems/integer-to-english-words/ Convert a non-negative integer to its englis ...

  4. LeetCode 273. Integer to English Words

    原题链接在这里:https://leetcode.com/problems/integer-to-english-words/description/ 题目: Convert a non-negati ...

  5. 273. Integer to English Words数字转为单词

    [抄题]: Convert a non-negative integer to its english words representation. Given input is guaranteed ...

  6. 273 Integer to English Words 整数转换英文表示

    将非负整数转换为其对应的英文表示,给定的输入是保证小于 231 - 1 的.示例:123 -> "One Hundred Twenty Three"12345 -> & ...

  7. leetcode-【hard】273. Integer to English Words

    题目: 273. Integer to English Words Convert a non-negative integer to its english words representation ...

  8. 【LeetCode】273. Integer to English Words

    Integer to English Words Convert a non-negative integer to its english words representation. Given i ...

  9. LeetCode 12 Integer to Roman (整数转罗马数字)

    题目链接: https://leetcode.com/problems/integer-to-roman/?tab=Description   String M[] = {"", ...

随机推荐

  1. python字符的表示格式

    %% 百分号标记 #就是输出一个% %c 字符及其ASCII码%s 字符串%d 有符号整数(十进制)%u 无符号整数(十进制)%o 无符号整数(八进制)%x 无符号整数(十六进制)%X 无符号整数(十 ...

  2. C++中的hash_map和map的区别

    hash_map和map的区别在哪里?构造函数.hash_map需要hash函数,等于函数:map只需要比较函数(小于函数). 存储结构.hash_map采用hash表存储,map一般采用红黑树(RB ...

  3. MATLAB中运算符优先级

    下述运算符的优先级从低到高: 1.先决或(||): 2.先决与(&&): 3.逻辑或(|): 4.逻辑与(&): 5.等于类(<,<=,>,>=,==, ...

  4. 注册服务到etcd中

    如上存放一些服务的key到etcd中,商品有两个,主要是为了负载均衡的key func NewService() *Service { config := clientv3.Config{ Endpo ...

  5. 洛谷 P1226 【模板】快速幂||取余运算 题解

    Analysis 快速幂模板,注意在最后输出时也要取模. 快速幂模板 inline ll ksm(ll x,ll y) { ll ans=; ) { ) { ans*=x; ans%=k; } x*= ...

  6. vue-cli 中的 eslint 规则说明

    "no-alert": 0,//禁止使用alert confirm prompt "no-array-constructor": 2,//禁止使用数组构造器 & ...

  7. 02-线性结构4 Pop Sequence (25 分)

    Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and p ...

  8. URL的作用是什么?它由几部分组成?

    URL是统一资源定位符,对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址.互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它 ...

  9. 「PKUSC2018」PKUSC

    传送门 Solution  考虑求每个点的贡献 等价于一个以OA长为半径的圆心为原点的圆在多边形内的弧对应的角度/\(2\pi\) 求弧度可以利用三角剖分 在原点的点要特判,采用射线法就可以了 Cod ...

  10. 京东Java架构师讲解购物车的原理及Java实现

    今天来写一下关于购物车的东西, 这里首先抛出四个问题: 1)用户没登陆用户名和密码,添加商品, 关闭浏览器再打开后 不登录用户名和密码问:购物车商品还在吗? 2)用户登陆了用户名密码,添加商品,关闭浏 ...