• 0273. Integer to English Words (H)


    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;
        }
    }
    
  • 相关阅读:
    黑马程序员_使用Jquery实现AJAX功能
    BootStrap 推荐网站
    工具类
    ExtJS 模块案例(增删改查)
    sql server 经典语句。~转 (入门必看)
    sql 时间格式转换
    转载wuhuacong(伍华聪)的专栏 利用Aspose.Word控件实现Word文档的操作 (留作笔记)
    c#操作Word文件 导出数据到word文档 (table 书签方式)
    ExtJs之格式化(Ext.util.Format) ~转
    查询/修改XML里某个字段的值
  • 原文地址:https://www.cnblogs.com/mapoos/p/13167336.html
Copyright © 2020-2023  润新知