算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 整数转换英文表示,我们先来看题面:
https://leetcode-cn.com/problems/integer-to-english-words/
Convert a non-negative integer num to its English words representation.
将非负整数 num 转换为其对应的英文表示。
示例
示例 1:
输入:num = 123
输出:"One Hundred Twenty Three"
示例 2:
输入:num = 12345
输出:"Twelve Thousand Three Hundred Forty Five"
示例 3:
输入:num = 1234567
输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:
输入:num = 1234567891
输出:"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
解题
这个是网上比较好理解的了 。
class Solution {
private final String[] THOUSAND = {"", "Thousand", "Million", "Billion"};
private final String[] LESS_THAN_TWENTY = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private final String[] HUNDRED = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
public String numberToWords(int num) {
if(num == 0) return "Zero";
StringBuilder sb = new StringBuilder();
int index = 0;
while(num > 0) {
if(num % 1000 != 0) {
StringBuilder tmp = new StringBuilder();
helper(num % 1000, tmp);
sb.insert(0, tmp.append(THOUSAND[index]).append(" "));
}
index++;
num /= 1000;
}
return sb.toString().trim();
}
private void helper(int num, StringBuilder tmp) {
if(num == 0) return;
if(num < 20) {
tmp.append(LESS_THAN_TWENTY[num]).append(" ");
}else if(num < 100) {
tmp.append(HUNDRED[num / 10]).append(" ");
helper(num % 10, tmp);
}else {
tmp.append(LESS_THAN_TWENTY[num / 100]).append(" Hundred").append(" ");
helper(num % 100, tmp);
}
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: