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:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
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;
    }
}
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄