Integer to English Words (H)
題目
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 One"
題意
將一個整數轉化成對應的英文字串,
思路
每三個數字加一個逗號,最多有3個逗號,將數字分成4個區間,每個區間有對應的后綴["", " Thousand", " Million", " Billion"],剩下的作業就是將每一個三位數轉化成對應的英文字串即可,需要注意的是當十位數字為1時英文形式要相應的改變,
代碼實作
Java
class Solution {
public String numberToWords(int num) {
// 0是特殊情況
if (num == 0) {
return "Zero";
}
String[] suffix = { "", " Thousand", " Million", " Billion" };
String[] ones = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
String[] sp = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; // 十位數為1時對應的英文串
String ans = "";
for (int i = 0; i < 4; i++) {
if (num == 0) {
break;
}
int cur = num % 1000; // 劃分當前三位數
int one = cur % 10, ten = cur % 100 / 10, hun = cur / 100; // 取出每一位上的數字
String s = "";
if (ten == 1) {
s = (hun == 0 ? "" : ones[hun] + " Hundred ") + sp[one];
} else {
s += hun == 0 ? "" : ones[hun] + " Hundred";
s += ten == 0 ? "" : (s.isEmpty() ? "" : " ") + tens[ten];
s += one == 0 ? "" : (s.isEmpty() ? "" : " ") + ones[one];
}
if (!s.isEmpty()) {
s += suffix[i];
ans = s + (ans.isEmpty() ? "" : " ") + ans;
}
num /= 1000;
}
return ans;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/43529.html
標籤:其他
