zoukankan      html  css  js  c++  java
  • LeetCode-Integer to English Words

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

    For example,

    123 -> "One Hundred Twenty Three" 12345 -> "Twelve Thousand Three Hundred Forty Five" 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

    Solution:

    BE CAREFUL: all kinds of corner cases

    public class Solution {
        String[] suffixs = new String[]{"","Thousand", "Million","Billion"};
        String[] tens = new String[]{"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty", "Ninety"};
        String[] tenTwenty = new String[]{"Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
        String[] singles = new String[]{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
        
        public String numberToWords(int num) {
            if (num==0) return "Zero";
            
            StringBuilder builder = new StringBuilder();
            int base = 1000;
            int index = 0;
            while (num!=0){
                int sectionNum = num%base;
                num = num / base;
                addSection(builder,sectionNum,suffixs[index++]);
            }
            return builder.toString().trim();
        }
        
        public void addSection(StringBuilder builder, int sectionNum, String suffix){
            if (sectionNum==0){
                return;
            }
            
            builder.insert(0," "+suffix);
            
            int hundreds = sectionNum / 100;
            int left = sectionNum % 100;
            
            if (left > 0){
                if (left<10){
                    builder.insert(0,singles[left]).insert(0," ");
                } else if (left>=10 && left < 20){
                    builder.insert(0,tenTwenty[left-10]).insert(0," ");
                } else {
                    String temp = " " + tens[left/10] + ((left%10==0) ? "" : (" " + singles[left%10]));
                    builder.insert(0,temp);
                }
            }
            
            if (hundreds>0){
                String temp = " " + singles[hundreds] + " Hundred";
                builder.insert(0,temp);
            }
        }
    }
  • 相关阅读:
    Linux Shell tr 命令详解
    Shell统计每个单词出现的个数
    启明4-29团队进度博客
    启明4-28团队进度博客
    启明4-27团队进度博客
    启明4-26团队进度博客
    启明4-25团队进度博客
    启明4-24团队博客
    每日总结8
    启明4-23团队进度博客
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5858592.html
Copyright © 2011-2022 走看看